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

Move db utility modules from self-contained to importable

This commit is contained in:
2022-02-26 23:17:56 +00:00
parent cc353694b6
commit ae9339e80d
2 changed files with 17 additions and 23 deletions

View File

@@ -13,7 +13,6 @@ 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,
@@ -251,14 +250,10 @@ tableConstraints.set('test_fk0', `
/**
* initialise() Initialises a database and applies the stratos schema to it
*
* @param {object} [dbOptions]
* - An object in the form found in config/db.json supplying the db to
* connect to
*
* @return {void}
*/
async function initialise(dbOptions) {
const dbConnectionPool = await new DatabaseConnectionPool(dbOptions);
async function initialise() {
const dbConnectionPool = await new DatabaseConnectionPool();
// Run the creation statment for each table
for (const [ tableName, sql ] of tableCreate) {
@@ -290,4 +285,4 @@ async function initialise(dbOptions) {
await dbConnectionPool.close();
}
initialise();
module.exports = initialise;

View File

@@ -478,33 +478,29 @@ const data = {
* cleanDb() Removes all records from the tables in the database to be inserted
* into
*
* @param {dbConnectionPool} [dbConnectionPool] - The database connection
*
* @return {void}
*/
async function cleanDb(dbConnectionPool) {
async function cleanDb() {
const conn = await new DatabaseConnectionPool();
// 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)
await dbConnectionPool.runQuery(`DELETE FROM ${table};`);
await conn.runQuery(`DELETE FROM ${table};`);
conn.close();
}
/**
* insertData() Inserts test data into a database
*
* @param {object} [dbOptions]
* - An object in the form found in config/db.json supplying the db to
* connect to
*
* @return {void}
*/
async function insertData(dbOptions) {
const dbConnectionPool = await new DatabaseConnectionPool(dbOptions);
await cleanDb(dbConnectionPool);
async function insertData() {
const conn = await new DatabaseConnectionPool();
// Run the creation statment for each table
for (const table of Object.keys(data)) {
@@ -558,7 +554,7 @@ async function insertData(dbOptions) {
console.log(sql.trim());
try {
await dbConnectionPool.runQuery(sql,
await conn.runQuery(sql,
Object.values(dataToInsert));
} catch (e) {
console.error(e);
@@ -568,7 +564,10 @@ async function insertData(dbOptions) {
}
}
await dbConnectionPool.close();
conn.close();
}
insertData();
module.exports = {
insert: insertData,
clean: cleanDb
};