Knex Utils
Common utilities for knex.js

** Connection init example
const config = require('config');
const { connectionUtils, heartbeatChecker } = require('knex-utils');
const HEARTBEAT_QUERY = heartbeatChecker.HEARTBEAT_QUERIES.POSTGRESQL;
const knexConfig = config.get('db');
let _knex;
function getKnexInstance() {
return _knex || _initKnexInstance();
}
function _initKnexInstance() {
_knex = connectionUtils.getKnexInstance(knexConfig, connectionUtils.getRegistry(), logger);
return _knex;
}
function checkHeartBeat() {
return heartbeatChecker.checkHeartbeat(_knex, HEARTBEAT_QUERY);
}
function close() {
if (_knex) {
const promise = _knex.destroy();
_knex = undefined;
connectionUtils.getRegistry().length = 0;
return promise;
}
return Promise.resolve();
}
module.exports = {
getKnexInstance,
checkHeartBeat,
close
};
** Hearbeat usage example
const { heartbeatChecker } = require('knex-utils');
const HEARTBEAT_QUERY = heartbeatChecker.HEARTBEAT_QUERIES.POSTGRESQL;
const knex = require('./db/db.service').getKnexInstance();
const appPromise = swaggerService.generateSwagger(true)
.then(async () => {
const dbCheckResult = await heartbeatChecker.checkHeartbeat(knex, HEARTBEAT_QUERY);;
if (dbCheckResult.isOk === false) {
console.error('DB connection error: ', dbCheckResult.error);
throw (dbCheckResult.error);
}
})
.then(async () => {
const app = express();
return app;
}
).catch((e) => {
console.error('Error while starting application: ', e);
throw e;
});
function getAppAsync() {
return appPromise;
}
module.exports = {
getAppAsync
};