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

Lint cleanup with new rules

This commit is contained in:
2022-03-03 09:14:09 +00:00
parent 80291efc6d
commit c9e826d016
20 changed files with 104 additions and 57 deletions

18
app.js
View File

@@ -45,7 +45,7 @@ async function main() {
// Set up express-session to store in mysql database
const mysqlStore = require('express-mysql-session')(session);
const sessionStore =
new mysqlStore({},(await new DatabaseConnectionPool()).pool);
new mysqlStore({}, (await new DatabaseConnectionPool()).pool);
// Initialise express app
const app = express();
@@ -82,9 +82,11 @@ async function main() {
}
}));
// Authentication middleware that redirects unauthenticated users
// back to the login page if they request a page they don't have access
// to
/*
* Authentication middleware that redirects unauthenticated users
* back to the login page if they request a page they don't have access
* to
*/
app.use((req, res, next) => {
const allowed = [
'/login',
@@ -116,9 +118,11 @@ async function main() {
for (const route of loadRoutes())
app.use(route[0], route[1]);
// If the request gets to the bottom of the route stack, it doesn't
// have a defined route and therefore a HTTP status code 404 is sent
// and an error page shown
/*
* If the request gets to the bottom of the route stack, it doesn't
* have a defined route and therefore a HTTP status code 404 is sent
* and an error page shown
*/
app.use((req, res) => {
res.status(404).render('error', {
title: 'Stratos - Error',

View File

@@ -1,7 +1,7 @@
'use strict';
// Import required modules
const { dest, parallel, series, src, watch } = require('gulp');
const { dest, parallel, series, src, watch } = require('gulp');
const del = require('del');
const fs = require('fs');
const path = require('path');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict';
const User = require('./User');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function */
'use strict';
const DatabaseConnectionPool = require('./DatabaseConnectionPool');
@@ -134,11 +135,11 @@ class Class {
})();
}
async getSubject() {
getSubject() {
return new (require('./Subject'))(this.subjectId);
}
async getUsers(ids, type) {
getUsers(ids, type) {
const types = {
account: 'Account',
student: 'Student'
@@ -212,4 +213,4 @@ class Class {
}
}
module.exports = Class;
module.exports = Class;

View File

@@ -14,6 +14,7 @@ const defaultDbOptions = importJSON('db');
*/
class DatabaseConnectionPool {
#dbOptions;
#connectionPool;
/**

View File

@@ -200,7 +200,7 @@ class EmailBuilder {
}
if (typeof this?.#HTMLBody?.length !== 'undefined')
message['html'] = this.#HTMLBody;
message.html = this.#HTMLBody;
return message;
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict';
const User = require('./User');

View File

@@ -7,8 +7,11 @@ const DatabaseConnectionPool = require('./DatabaseConnectionPool');
class PasswordReset {
userId;
token;
nonce;
expires;
constructor(userId, token) {

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict';
const User = require('./User');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict';
// Import user defined modules
@@ -105,11 +106,11 @@ class Test {
})();
}
async getClass() {
getClass() {
return new (require('./Class'))(this.classId);
}
async getTestTemplate() {
getTestTemplate() {
return new (require('./TestTemplate'))(this.templateId);
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict';
// Import user defined modules
@@ -73,7 +74,7 @@ class TestTemplate {
})();
}
async getAccount() {
getAccount() {
return new (require('./Account'))(this.accountId);
}

View File

@@ -11,13 +11,21 @@ const Test = require('./Test');
class User {
id;
firstName;
otherNames;
lastName;
shortName;
fullName;
email;
#password;
type = null;
constructor(type, userId) {
@@ -33,6 +41,9 @@ class User {
}
return (async () => {
const conn = await new DatabaseConnectionPool();
const queryPromises = [];
for (const type of types) {
const sql = `
select
@@ -48,19 +59,27 @@ class User {
${type}Id = ?;
`;
const conn = await new DatabaseConnectionPool();
const res =
await conn.runQuery(sql, [ userId ]);
queryPromises.push(conn.runQuery(sql, [
userId
]));
}
conn.close();
const typeResults = await Promise.all(queryPromises);
conn.close();
if (!res.length)
for (const [ i, result ] of typeResults.entries()) {
if (!result.length)
continue;
const record = res[0];
const record = result[0];
const type = types[i];
for (const [ k, v ] of Object.entries(record))
this[k] = v;
for (const [ k, v ] of Object.entries(record)) {
if (k === 'password')
this.#password = v;
else
this[k] = v;
}
this.type = type;
this.shortName = this.getShortName();
@@ -70,8 +89,8 @@ class User {
return this;
const className =
`${type.substring(0, 1).toUpperCase()}`
+ `${type.substring(1)}`;
`${type.substring(0, 1).toUpperCase()}`+
`${type.substring(1)}`;
return new (require(`./${className}`))(this.id);
}
@@ -94,7 +113,7 @@ class User {
}
async verifyPassword(password) {
return await bcrypt.compare(password, this.password);
return await bcrypt.compare(password, this.#password);
}
async changePassword(password) {
@@ -173,7 +192,7 @@ class User {
if (this.type === 'parent')
throw new Error(`Can not fetch class for ${this.type}`);
let sql = `
const sql = `
select
c.classId as classId
from
@@ -243,6 +262,8 @@ class User {
const conn = await new DatabaseConnectionPool();
const types = [ 'account', 'student', 'parent' ];
const idPromises = [];
for (const type of types) {
const sql = `
select
@@ -253,18 +274,24 @@ class User {
email = ?;
`;
const id = (await conn.runQuery(sql, [
idPromises.push(conn.runQuery(sql, [
email
]))?.[0]?.['id'];
]));
}
const ids = await Promise.all(idPromises);
for (const [ i, records ] of ids.entries()) {
const type = types[i];
const id = records?.[0]?.id;
if (typeof id !== 'undefined') {
const className =
`${type.substring(0, 1).toUpperCase()}`
+ `${type.substring(1)}`;
`${type.substring(0, 1).toUpperCase()}`+
`${type.substring(1)}`;
return new (require(`./${className}`))(id);
}
}
}
}

View File

@@ -66,7 +66,7 @@ describe('DatabaseConnectionPool', () => {
expect(() => dbp.runQuery(sql, params)).toThrow();
});
test('Query with whitespace after ; should not fail', ()=> {
test('Query with whitespace after ; should not fail', () => {
const dbp = new DatabaseConnectionPool();
const sql = `

View File

@@ -3,6 +3,6 @@
const helpers = {};
helpers.eq = (arg1, arg2, options) =>
arg1 == arg2 ? options.fn(this) : options.inverse(this);
arg1 === arg2 ? options.fn(this) : options.inverse(this);
module.exports = helpers;

View File

@@ -38,9 +38,7 @@ function passwordsMatch(password1, password2) {
* @return {string} - The sanitisied field
*/
function sanitiseField(field) {
let cleanField;
cleanField = field.trim();
const cleanField = field.trim();
return cleanField;
}

View File

@@ -171,7 +171,7 @@ router.get('/password-reset/:uuid/:token', async (req, res) => {
let pr;
try {
pr = await new PasswordReset(uuid, token);
} catch(e) {
} catch (e) {
console.error(e);
return res.redirect('/password-reset');
}
@@ -214,7 +214,7 @@ router.post('/change-password', async (req, res) => {
fields.get('uuid'),
fields.get('token')
);
} catch(e) {
} catch (e) {
console.error(e);
return res.redirect('/password-reset');
}

View File

@@ -4,13 +4,15 @@ const express = require('express');
const router = express.Router();
router.get('/reports', (req, res, next) => {
/*
/* eslint-disable multiline-comment-style */
/*
return res.render('reports', {
title: 'Stratos - Reports',
current: 'Reports',
name: req.session.fullName
});
*/
*/
/* eslint-enable multiline-comment-style */
next();
});

View File

@@ -19,12 +19,15 @@ const { data } = require('./testData');
async function cleanDb() {
const conn = await new DatabaseConnectionPool();
// Remove records from tables in reverse order to which they depend on
// each other
/*
* Remove records from tables in reverse order to which they depend on
* each other
*/
const tables = Object.keys(data).reverse();
tables.push('sessions');
for (const table of tables)
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(`DELETE FROM ${table};`);
conn.close();

View File

@@ -12,7 +12,6 @@ const tableCreate = new Map();
const tableConstraints = new Map();
// For each table, set tableCreate.tableName equal to the creation statment
// for that table
tableCreate.set('account', `
CREATE TABLE IF NOT EXISTS account (
accountId varchar(36) NOT NULL PRIMARY KEY,
@@ -128,8 +127,10 @@ tableCreate.set('accountClassLink', `
);
`);
// For each table constraint, set tableConstraints.constraitName equal to the
// creation statment for that constraint
/*
* For each table constraint, set tableConstraints.constraintName equal to the
* creation statment for that constraint
*/
tableConstraints.set('accountClassLink_fk0', `
ALTER TABLE accountClassLink
ADD CONSTRAINT accountClassLink_fk0
@@ -260,6 +261,7 @@ async function dbInit() {
console.log(`Creating table ${tableName}`);
try {
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(sql);
} catch (e) {
console.error(e);
@@ -274,6 +276,7 @@ async function dbInit() {
console.log(`Creating constraint ${fkName}`);
try {
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(sql);
} catch (e) {
console.error(e);

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-await-in-loop */
'use strict';
// Import required modules
@@ -27,34 +28,33 @@ async function insertTestData() {
for (const record of data[table]) {
const dataToInsert = { ...record };
if (details?.[table]?.['id'] === 'uuid') {
if (details?.[table]?.id === 'uuid') {
dataToInsert[`${table}Id`] =
crypto.randomUUID();
} else {
dataToInsert[`${table}Id`] = counter + 1;
}
if (details?.[table]?.['hashPassword']) {
dataToInsert['password'] =
if (details?.[table]?.hashPassword) {
dataToInsert.password =
await bcrypt.hash(
dataToInsert['password'],
dataToInsert.password,
10);
}
if (details?.[table]?.['link'])
if (details?.[table]?.link)
delete dataToInsert[`${table}Id`];
if (record?.lookups) {
delete dataToInsert.lookups;
const lookupsEntries =
Object.entries(record.lookups);
for (let [ key, index ] of
Object.entries(record.lookups)) {
for (const [ key, index ] of lookupsEntries) {
const resolveTable = key.split('Id')[0];
index--;
const r = data[resolveTable][index - 1];
dataToInsert[key] =
data[resolveTable][index][key];
dataToInsert[key] = r[key];
}
}