38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
export const DEFAULT_TEST_DATABASE_URL =
|
|
"postgresql://drift:drift_test_only@127.0.0.1:55432/drift_bottle_test?schema=public";
|
|
|
|
const SAFETY_ERROR =
|
|
"Refusing database operation: DATABASE_URL must target localhost or 127.0.0.1 and a database ending in _test.";
|
|
|
|
export function assertSafeTestDatabaseUrl(databaseUrl: string): void {
|
|
try {
|
|
const parsed = new URL(databaseUrl);
|
|
const isLocal =
|
|
parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
|
|
const databaseName = decodeURIComponent(parsed.pathname.slice(1));
|
|
if (
|
|
parsed.protocol !== "postgresql:" ||
|
|
!isLocal ||
|
|
!databaseName.endsWith("_test")
|
|
) {
|
|
throw new Error(SAFETY_ERROR);
|
|
}
|
|
} catch {
|
|
throw new Error(SAFETY_ERROR);
|
|
}
|
|
}
|
|
|
|
export function resolveTestDatabaseUrl(environment = process.env): string {
|
|
const databaseUrl = environment.DATABASE_URL ?? DEFAULT_TEST_DATABASE_URL;
|
|
assertSafeTestDatabaseUrl(databaseUrl);
|
|
return databaseUrl;
|
|
}
|
|
|
|
export function assertSeedDatabaseAllowed(
|
|
databaseUrl: string,
|
|
environment = process.env,
|
|
): void {
|
|
if (environment.ALLOW_SEED_NON_TEST_DATABASE === "true") return;
|
|
assertSafeTestDatabaseUrl(databaseUrl);
|
|
}
|