qualiteer/lib/database/postgres.js
2022-07-12 21:26:36 +00:00

53 lines
1.4 KiB
JavaScript

// Imports
import { migrate } from "postgres-migrations";
import createPgp from "pg-promise";
import moment from "moment";
import { INFO, WARN } from "../util/logging.js";
// Environment Variables
const {
POSTGRES_DATABASE: database,
POSTGRES_DISABLED: pgDisabled,
POSTGRES_HOST: host,
POSTGRES_PASSWORD: password,
POSTGRES_PORT: port,
POSTGRES_USER: user,
} = process.env;
// Postgres-promise Configuration
// Ensure dates get saved as UTC date strings
// This prevents the parser from doing strange datetime operations
const pgp = createPgp();
pgp.pg.types.setTypeParser(1114, (str) => moment.utc(str).format());
// Database Config
const dbConfig = {
database: database ?? "qualiteer",
user: user ?? "postgres",
password: password ?? "postgres",
host: host ?? "localhost",
port: port ?? 5432,
ensureDatabaseExists: true,
};
const migrationsDir = "lib/database/migrations";
const queryMock = (str) => INFO("POSTGRES MOCK", str);
const connect = (pg) => async () => {
if (pgDisabled) {
WARN("POSTGRES", "Postgres Disabled!");
return { query: queryMock };
}
await migrate(dbConfig, migrationsDir);
// Override the global variable DB
pg = pgp(dbConfig);
await pg.connect();
OK("POSTGRES", `Connected to database ${database}!`);
};
const buildPostgres = () => {
var pg = { query: queryMock, connect: connect(pg) };
return pg;
};
export default buildPostgres;