@coko/server
Version:
Reusable server for use by Coko's projects
50 lines • 1.98 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const knex_1 = __importDefault(require("knex"));
const objection_1 = require("objection");
const config_1 = __importDefault(require("../configManager/config"));
const connectionConfig_1 = __importDefault(require("./connectionConfig"));
// Attach to dummy function instead of class so that we can call db as a
// function (eg. db(table_name).select(...))
const manager = Object.assign(() => { }, {
instance: null,
init() {
if (this.instance)
return;
const connectionConfig = (0, connectionConfig_1.default)();
const pool = config_1.default.has('pool') && config_1.default.get('pool');
const acquireConnectionTimeout = config_1.default.get('acquireConnectionTimeout');
this.instance = (0, knex_1.default)({
client: 'pg',
connection: connectionConfig,
pool,
...(0, objection_1.knexSnakeCaseMappers)(),
acquireConnectionTimeout,
asyncStackTraces: true,
});
},
});
const db = new Proxy(manager, {
// get will intercept all db.someMethod or db.someProperty calls
get(target, prop) {
if (prop === 'init')
return target.init.bind(target);
if (!target.instance) {
throw new Error('Database not initialized. Run db.init() first.');
}
const value = target.instance[prop];
return typeof value === 'function' ? value.bind(target.instance) : value;
},
// apply will intercept all db(someArg) calls
apply(target, _, args) {
if (!target.instance) {
throw new Error('Database not initialized. Run db.init() first.');
}
return target.instance(...args);
},
});
exports.default = db;
//# sourceMappingURL=db.js.map