From 95b1636288a8c6512b32bf4fffc9e7d7205266f6 Mon Sep 17 00:00:00 2001 From: matt Date: Fri, 1 Apr 2022 12:46:07 +0000 Subject: [PATCH] Reduce overhead on calls to getStudents and getTeacher to not fetch objects when they're not required --- lib/Class.js | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/lib/Class.js b/lib/Class.js index b579d1b..4408a1c 100644 --- a/lib/Class.js +++ b/lib/Class.js @@ -95,8 +95,12 @@ class Class { this.getSubject() ]); - this.teachers = teachers; - this.students = students; + this.teachers = teachers.objs; + this.teacherIds = teachers.ids; + + this.students = students.objs; + this.studentIds = students.ids; + this.subject = subject; return this; @@ -107,7 +111,7 @@ class Class { return new (require('./Subject'))(this.#conn, this.subjectId); } - async getTeachers() { + async getTeachers(fetchObjects = true) { const sql = ` select a.accountId as id @@ -121,14 +125,19 @@ class Class { const res = await this.#conn.runQuery(sql, [ this.id ]); - this.teacherIds = res.map(record => record.id); + const ids = res.map(record => record.id); - this.teachers = await this.getUsers(this.teacherIds, 'account'); + if (!fetchObjects) + return { ids: ids }; - return this.teachers; + const teachers = await this.getUsers( + ids, + 'account'); + + return { ids: ids, objs: teachers }; } - async getStudents() { + async getStudents(fetchObjects = true) { const sql = ` select s.studentId as id @@ -141,11 +150,16 @@ class Class { const res = await this.#conn.runQuery(sql, [ this.id ]); - this.studentIds = res.map(record => record.id); + const ids = res.map(record => record.id); - this.students = await this.getUsers(this.studentIds, 'student'); + if (!fetchObjects) + return { ids: ids }; - return this.students; + const students = await this.getUsers( + ids, + 'student'); + + return { ids: ids, objs: students }; } getUsers(ids, type) { @@ -244,9 +258,9 @@ class Class { if (!validTypes.includes(u.type)) throw new Error('Invalid user type'); - this.teachers = await this.getTeachers(); + const teachers = (await this.getTeachers(false)).ids; - if (u.type === 'account' && this.teachers.length < 2) + if (u.type === 'account' && teachers.length < 2) throw new Error('Can\'t remove last teacher'); const sql = `