import * as moment from "moment"; import {Moment} from "moment"; import * as pgPromise from "pg-promise"; const readDelta = 1; export function dbConfigCtor(pgPromise) { let settings: { databaseUrlRead: any, databaseUrlWrite: any, databaseUrlDelete: any, [name:string]: any }; let dbProvider: any = null; let nextRead: Moment = moment().add(-readDelta, "minutes"); return { async execute() { try { const now = moment(); if (!dbProvider) { dbProvider = pgPromise()(process.env.DATABASE_URL_CONFIG); } if (!nextRead || nextRead <= now) { const defaultEnv = "dev"; const configEnv = process.env.CONFIG_ENV || defaultEnv; const rows = await dbProvider.one( "SELECT settings FROM config WHERE env=$(CONFIG_ENV) AND effective < now() ORDER BY effective DESC LIMIT 1", {CONFIG_ENV: configEnv}, ); if (rows && rows.settings) { settings = rows.settings; } else { // noinspection ExceptionCaughtLocallyJS throw new Error(`Could not load config settings for environment ${configEnv}`); } nextRead = now.add(readDelta, "minutes"); } return settings; } catch (e) { console.error(`unable to load dbConfig: ${e}`); throw e; } }, }; } export const dbConfig = dbConfigCtor(pgPromise).execute;