qualiteer/lib/database/postgres.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-05-05 12:35:47 +00:00
// Imports
import { migrate } from "postgres-migrations";
import createPgp from "pg-promise";
import moment from "moment";
2022-05-17 12:32:04 +00:00
import { INFO, WARN } from "../util/logging.js";
2022-05-05 12:35:47 +00:00
// 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";
2022-07-12 21:26:36 +00:00
const queryMock = (str) => INFO("POSTGRES MOCK", str);
const connect = (pg) => async () => {
2022-05-05 12:35:47 +00:00
if (pgDisabled) {
WARN("POSTGRES", "Postgres Disabled!");
2022-07-12 21:26:36 +00:00
return { query: queryMock };
2022-05-05 12:35:47 +00:00
}
await migrate(dbConfig, migrationsDir);
// Override the global variable DB
2022-07-12 21:26:36 +00:00
pg = pgp(dbConfig);
2022-05-05 12:35:47 +00:00
await pg.connect();
OK("POSTGRES", `Connected to database ${database}!`);
2022-07-12 21:26:36 +00:00
};
const buildPostgres = () => {
var pg = { query: queryMock, connect: connect(pg) };
2022-05-05 12:35:47 +00:00
return pg;
};
2022-07-12 21:26:36 +00:00
export default buildPostgres;