diff --git a/lib/Class.js b/lib/Class.js index 617ab60..076f21a 100644 --- a/lib/Class.js +++ b/lib/Class.js @@ -1,6 +1,7 @@ 'use strict'; const DatabaseConnectionPool = require('./DatabaseConnectionPool'); +const Test = require('./Test'); class Class { /** @@ -109,8 +110,45 @@ class Class { return Promise.all(teacherPromises); } - get tests() { + async getTests({ order='desc', range='all' } = {}) { + const validOrder = [ 'asc', 'desc' ]; + const validRange = [ 'all', 'before', 'after' ]; + if (!validOrder.includes(order)) + throw new Error('Invalid order'); + + if (!validRange.includes(range)) + throw new Error('Invalid range'); + + let sql = ` + select + t.testId as testId + from + class c + join test t using(classId) + where + c.classId = ? + `; + + switch (range) { + case 'before': + sql += 'and t.testDate <= curdate()'; + break; + case 'after': + sql += 'and t.testDate > curdate()'; + break; + } + + sql += `order by t.testDate ${order};`; + + const conn = await new DatabaseConnectionPool(); + const tests = await conn.runQuery(sql, [ this.id ]); + + const testObjects = tests.map(test => { + return new Test(test.testId); + }); + + return await Promise.all(testObjects); } get students() {