From 1b2dfe568180dfd11846775ac56df68ff6187b21 Mon Sep 17 00:00:00 2001 From: matt Date: Mon, 14 Feb 2022 00:19:28 +0000 Subject: [PATCH] Rewrite User constructor to search all tables if no type given --- lib/User.js | 52 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/lib/User.js b/lib/User.js index 46d2302..fea9ddb 100644 --- a/lib/User.js +++ b/lib/User.js @@ -15,29 +15,45 @@ class User { type = null; constructor(type, userId) { - const sql = ` - select - email, - firstName, - otherNames, - lastName, - password, - accountId as id - from ${type} - where - ${type}Id = ?; - `; + type = type ?? false; - this.type = type; + let types = []; + if (type) + types.push(type); + else + types = [ 'account', 'student', 'parent' ]; return (async () => { - const conn = await new DatabaseConnectionPool(); - const record = await conn.runQuery(sql, [ userId ]); + for (const type of types) { + const sql = ` + select + email, + firstName, + otherNames, + lastName, + password, + accountId as id + from ${type} + where + ${type}Id = ?; + `; - for (const [ k, v ] of Object.entries(record[0])) - this[k] = v; + const conn = await new DatabaseConnectionPool(); + const res = + await conn.runQuery(sql, [ userId ]); - return this; + if (!res) + continue; + + const record = res[0]; + + for (const [ k, v ] of Object.entries(record)) + this[k] = v; + + this.type = type; + + return this; + } })(); }