bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
2.19 kB
import { Pool } from "pg";
const TEST_DATABASE_HOST = "127.0.0.1";
const TEST_DATABASE_PORT = "55432";
const TEST_DATABASE_NAME = "mike_test";
let pool: Pool | null = null;
let activeConnectionString: string | null = null;
function isIntegrationTestMode() {
return (
process.env.MIKE_INTEGRATION_TEST === "1" || process.env.NODE_ENV === "test"
);
}
export function validateTestDatabaseUrl(connectionString: string) {
if (!connectionString) {
throw new Error("TEST_DATABASE_URL is required");
}
let parsed: URL;
try {
parsed = new URL(connectionString);
} catch {
throw new Error("Invalid TEST_DATABASE_URL");
}
if (parsed.protocol !== "postgres:") {
throw new Error("Invalid protocol, must be postgres:");
}
if (parsed.hostname !== TEST_DATABASE_HOST) {
throw new Error(`Invalid hostname, must be ${TEST_DATABASE_HOST}`);
}
if (parsed.port !== TEST_DATABASE_PORT) {
throw new Error(`Invalid port, must be ${TEST_DATABASE_PORT}`);
}
if (parsed.pathname !== `/${TEST_DATABASE_NAME}`) {
throw new Error(`Invalid database name, must be ${TEST_DATABASE_NAME}`);
}
}
export function resolveDatabaseUrl() {
const explicitTestUrl = process.env.TEST_DATABASE_URL;
if (explicitTestUrl) {
validateTestDatabaseUrl(explicitTestUrl);
return explicitTestUrl;
}
if (isIntegrationTestMode()) {
throw new Error(
"TEST_DATABASE_URL is required during integration tests and must target the disposable mike_test database",
);
}
return (
process.env.DATABASE_URL || "postgres://mike:mike123@127.0.0.1:5432/mike"
);
}
export function getDatabasePool() {
const connectionString = resolveDatabaseUrl();
if (!pool || activeConnectionString !== connectionString) {
pool = new Pool({ connectionString });
activeConnectionString = connectionString;
}
return pool;
}
export async function closeDatabasePool() {
if (!pool) {
return;
}
const currentPool = pool;
pool = null;
activeConnectionString = null;
await currentPool.end();
}
export const TEST_DATABASE_TARGET = {
host: TEST_DATABASE_HOST,
port: TEST_DATABASE_PORT,
databaseName: TEST_DATABASE_NAME,
};