From 0fa2310f39163629bcdc5619a2a44342e96dd620 Mon Sep 17 00:00:00 2001 From: matt Date: Thu, 20 Jan 2022 01:35:30 +0000 Subject: [PATCH] Added database interface module --- lib/DatabaseConnectionPool.js | 65 +++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 lib/DatabaseConnectionPool.js diff --git a/lib/DatabaseConnectionPool.js b/lib/DatabaseConnectionPool.js new file mode 100644 index 0000000..752af64 --- /dev/null +++ b/lib/DatabaseConnectionPool.js @@ -0,0 +1,65 @@ +'use strict'; + +// Import required modules +const mysql = require('mysql2/promise'); +const path = require('path'); + +// Import the database connection options from config/db.json +let defaultDbOptions; +try { + defaultDbOptions = require( + path.join(__dirname, '../config/db.json')); +} catch (e) { + console.log(e); + throw new Error('Missing or malformed config ' + + '(config/db.json)'); +} + +/** + * A class representing a pool of database connections + */ +class DatabaseConnectionPool { + #dbOptions; + #connectionPool; + + /** + * Create a database connection pool + * @param {object} [dbOptions] Optional database params to connect with + */ + constructor(dbOptions) { + // Use default options if none are passed into the constructor + if (typeof dbOptions === 'undefined') + this.#dbOptions = defaultDbOptions; + + return (async () => { + this.#connectionPool = + await mysql.createPool(this.#dbOptions); + + return this; + })(); + } + + /** + * Run a query against the database connection + * @param {string} sql The query to be executed + * @param {(Array)} Values to replace prepared statement + * @return {(Array|object)} Data returned from the database + */ + async runQuery(sql, params) { + if (sql.slice(-1) !== ';') + throw new Error('Invalid query, needs ;'); + + // Execute as non-prepared if no params are supplied + if (typeof params === 'undefined') { + const [ data ] = + await this.#connectionPool.execute(sql); + return data; + } + + const [ data ] = + await this.#connectionPool.execute(sql, params); + return data; + } +} + +module.exports = DatabaseConnectionPool;