qualiteer/lib/server/database/postgres.js

64 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-05-05 12:35:47 +00:00
// Imports
2022-10-15 11:47:47 +00:00
import path from "node:path";
import { URL } from "node:url";
2022-05-05 12:35:47 +00:00
import { migrate } from "postgres-migrations";
import createPgp from "pg-promise";
import moment from "moment";
2022-10-08 17:47:46 +00:00
import { INFO, WARN, OK, VERB } from "../util/logging.js";
2023-03-19 13:53:37 -04:00
2022-05-05 12:35:47 +00:00
// Environment Variables
const {
2022-10-08 17:47:46 +00:00
QUALITEER_POSTGRES_DATABASE: database,
QUALITEER_POSTGRES_ENABLED: pgEnabled,
QUALITEER_POSTGRES_HOST: host,
QUALITEER_POSTGRES_PASSWORD: password,
QUALITEER_POSTGRES_PORT: port,
QUALITEER_POSTGRES_USER: user,
2022-05-05 12:35:47 +00:00
} = 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,
};
2022-10-15 11:47:47 +00:00
const databaseDir = new URL(".", import.meta.url).pathname;
const migrationsDir = path.resolve(databaseDir, "migrations/");
2022-05-05 12:35:47 +00:00
2022-07-12 21:26:36 +00:00
const queryMock = (str) => INFO("POSTGRES MOCK", str);
const connect = (pg) => async () => {
2022-10-08 17:47:46 +00:00
if (pgEnabled === "false") {
2022-05-05 12:35:47 +00:00
WARN("POSTGRES", "Postgres Disabled!");
2022-07-12 21:26:36 +00:00
return { query: queryMock };
2022-05-05 12:35:47 +00:00
}
2022-10-08 17:47:46 +00:00
VERB("POSTGRES", "Migrating...");
2022-05-05 12:35:47 +00:00
await migrate(dbConfig, migrationsDir);
2022-10-08 17:47:46 +00:00
// Override fake methods
const pgInstance = pgp(dbConfig);
for (var k in pgInstance) pg[k] = pgInstance[k];
2023-03-19 13:53:37 -04:00
VERB("POSTGRES", "Migrated Successfully!");
2022-05-05 12:35:47 +00:00
await pg.connect();
2022-10-08 17:47:46 +00:00
VERB("POSTGRES", "Postgres connected Successfully!");
OK("POSTGRES", `Connected to database ${dbConfig.database}!`);
2022-07-12 21:26:36 +00:00
};
const buildPostgres = () => {
2022-10-08 17:47:46 +00:00
var pg = { query: queryMock };
pg.connect = connect(pg);
2022-05-05 12:35:47 +00:00
return pg;
};
2022-10-08 17:47:46 +00:00
export default buildPostgres();