63 lines
1.8 KiB
JavaScript
63 lines
1.8 KiB
JavaScript
// Imports
|
|
import path from "node:path";
|
|
import { URL } from "node:url";
|
|
import { migrate } from "postgres-migrations";
|
|
import createPgp from "pg-promise";
|
|
import moment from "moment";
|
|
import { INFO, WARN, OK, VERB } from "../util/logging.js";
|
|
|
|
// Environment Variables
|
|
const {
|
|
MCL_POSTGRES_DATABASE: database,
|
|
MCL_POSTGRES_ENABLED: pgEnabled,
|
|
MCL_POSTGRES_HOST: host,
|
|
MCL_POSTGRES_PASS: password,
|
|
MCL_POSTGRES_PORT: port,
|
|
MCL_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 ?? "minecluster",
|
|
user: user ?? "postgres",
|
|
password: password ?? "postgres",
|
|
host: host ?? "localhost",
|
|
port: port ?? 5432,
|
|
ensureDatabaseExists: true,
|
|
};
|
|
|
|
const databaseDir = new URL(".", import.meta.url).pathname;
|
|
const migrationsDir = path.resolve(databaseDir, "migrations/");
|
|
|
|
const queryMock = (str) => INFO("POSTGRES MOCK", str);
|
|
|
|
const connect = (pg) => async () => {
|
|
if (pgEnabled === "false") {
|
|
WARN("POSTGRES", "Postgres Disabled!");
|
|
return { query: queryMock };
|
|
}
|
|
VERB("POSTGRES", "Migrating...");
|
|
await migrate(dbConfig, migrationsDir);
|
|
// Override fake methods
|
|
const pgInstance = pgp(dbConfig);
|
|
for (var k in pgInstance) pg[k] = pgInstance[k];
|
|
VERB("POSTGRES", "Migrated Successfully!");
|
|
await pg.connect();
|
|
VERB("POSTGRES", "Postgres connected Successfully!");
|
|
|
|
OK("POSTGRES", `Connected to database ${dbConfig.database}!`);
|
|
};
|
|
|
|
const buildPostgres = () => {
|
|
var pg = { query: queryMock };
|
|
pg.connect = connect(pg);
|
|
return pg;
|
|
};
|
|
|
|
export default buildPostgres();
|