Skip to content

Commit

Permalink
[OGUI-1544] Check db connection on server start (#2584)
Browse files Browse the repository at this point in the history
adds initial check for connection on DB to enable service in the GUI for users;
  • Loading branch information
graduta authored Sep 8, 2024
1 parent 8cc14ae commit 5ad6477
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
1 change: 1 addition & 0 deletions InfoLogger/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports.attachTo = async (http, ws) => {

if (config.mysql) {
queryService = new QueryService(config.mysql);
queryService.checkConnection(1, false);
}
const queryController = new QueryController(queryService);

Expand Down
24 changes: 16 additions & 8 deletions InfoLogger/lib/services/QueryService.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ class QueryService {
* @param {object} configMySql - mysql config
*/
constructor(configMySql = {}) {
configMySql._user = configMySql?.user ?? 'gui';
configMySql._password = configMySql?.password ?? '';
configMySql._host = configMySql?.host ?? 'localhost';
configMySql._port = configMySql?.port ?? 3306;
configMySql._database = configMySql?.database ?? 'info_logger';
configMySql._connectionLimit = configMySql?.connectionLimit ?? 25;
configMySql.user = configMySql?.user ?? 'gui';
configMySql.password = configMySql?.password ?? '';
configMySql.host = configMySql?.host ?? 'localhost';
configMySql.port = configMySql?.port ?? 3306;
configMySql.database = configMySql?.database ?? 'info_logger';
configMySql.connectionLimit = configMySql?.connectionLimit ?? 25;
this._timeout = configMySql?.timeout ?? 10000;
this._host = configMySql.host;
this._port = configMySql.port;

this._pool = mariadb.createPool(configMySql);
this._isAvailable = false;
Expand All @@ -38,18 +40,24 @@ class QueryService {
/**
* Method to test connection of mysql connector once initialized
* @param {number} timeout - timeout for the connection test
* @param {boolean} shouldThrow - whether an error should be thrown on failure
* @returns {Promise} - a promise that resolves if connection is successful
*/
async checkConnection(timeout = this._timeout) {
async checkConnection(timeout = this._timeout, shouldThrow = true) {
try {
await this._pool.query({
sql: 'SELECT 1',
timeout,
});
this._isAvailable = true;
this._logger.infoMessage(`Connection to DB successfully established: ${this._host}:${this._port}`);
} catch (error) {
this._isAvailable = false;
fromSqlToNativeError(error);
if (shouldThrow) {
fromSqlToNativeError(error);
} else {
this._logger.errorMessage(error);
}
}
}

Expand Down

0 comments on commit 5ad6477

Please sign in to comment.