1
0
mirror of https://github.com/matt-fidd/stratos.git synced 2026-01-01 17:59:25 +00:00

Refactored database connection system to use a shared pool per-request

This commit is contained in:
2022-03-23 23:29:55 +00:00
parent bd662661ee
commit 4c2a078530
14 changed files with 162 additions and 144 deletions

View File

@@ -3,8 +3,6 @@
const crypto = require('crypto');
const DatabaseConnectionPool = require('./DatabaseConnectionPool');
const Subject = require('./Subject');
const Test = require('./Test');
@@ -57,10 +55,14 @@ class Class {
*/
students;
#conn;
/**
* @param {string} classID - The id of the class to fetch
*/
constructor(classId) {
constructor(conn, classId) {
this.#conn = conn;
const sql = `
select
classId as id,
@@ -95,9 +97,7 @@ class Class {
`;
return (async () => {
const conn = await new DatabaseConnectionPool();
const record = await conn.runQuery(sql, [
const record = await this.#conn.runQuery(sql, [
classId
]);
@@ -108,16 +108,14 @@ class Class {
this[k] = v;
const [ teacherRes, studentRes ] = await Promise.all([
conn.runQuery(teacherSQL, [
this.#conn.runQuery(teacherSQL, [
classId
]),
conn.runQuery(studentSQL, [
this.#conn.runQuery(studentSQL, [
classId
])
]);
conn.close();
this.teacherIds = teacherRes.map(record => record.id);
this.studentIds = studentRes.map(record => record.id);
@@ -140,7 +138,7 @@ class Class {
}
getSubject() {
return new (require('./Subject'))(this.subjectId);
return new (require('./Subject'))(this.#conn, this.subjectId);
}
getUsers(ids, type) {
@@ -153,7 +151,8 @@ class Class {
throw new Error('Invalid type');
const promises = ids.map(id => {
return new (require(`./${types[type]}`))(id);
const classFile = `./${types[type]}`;
return new (require(classFile))(this.#conn, id);
});
return Promise.all(promises);
@@ -190,11 +189,10 @@ class Class {
sql += `order by t.testDate ${order};`;
const conn = await new DatabaseConnectionPool();
const tests = await conn.runQuery(sql, [ this.id ]);
const tests = await this.#conn.runQuery(sql, [ this.id ]);
const testObjects = tests.map(test => {
return new Test(test.testId);
return new Test(this.#conn, test.testId);
});
return await Promise.all(testObjects);
@@ -220,14 +218,12 @@ class Class {
}
static async createClass(accountId, name, subjectId) {
const s = await new Subject(subjectId);
const a = await new (require('./Account'))(accountId);
static async createClass(conn, accountId, name, subjectId) {
const s = await new Subject(conn, subjectId);
const a = await new (require('./Account'))(conn, accountId);
const id = crypto.randomUUID();
const conn = await new DatabaseConnectionPool();
let sql = `
insert into class(
classId,
@@ -256,7 +252,7 @@ class Class {
id
]);
return new Class(id);
return new Class(conn, id);
}
}