Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/seed.server.ts
T

84 lines
2.6 KiB
TypeScript

export type SeedEnvironment = "production" | "development" | "test" | (string & {});
export type DbSeedDiagnosticPhase = "start" | "success" | "failure";
export type DbSeedDiagnosticEvent = {
phase: DbSeedDiagnosticPhase;
nodeEnv: SeedEnvironment;
adminEmail?: string;
error?: unknown;
};
export type DbSeedDiagnostics = (event: DbSeedDiagnosticEvent) => void | Promise<void>;
export type DbSeedCallback<TResult = void> = () => Promise<TResult> | TResult;
export type SeedCredential = {
label?: string;
email?: string;
password?: string;
};
export type SafeSeedCredentialOptions = {
nodeEnv?: SeedEnvironment;
adminEmail?: string;
adminPassword?: string;
seedCredentials?: SeedCredential[];
};
export type RunDbSeedOptions<TResult = void> = SafeSeedCredentialOptions & {
seed: DbSeedCallback<TResult>;
diagnostics?: DbSeedDiagnostics;
};
const DEFAULT_ADMIN_PASSWORD = "password";
const DEFAULT_SEED_EMAILS = new Set(["admin@email.com", "john.doe@company.com", "luna.davis@company.com"]);
export function assertSafeSeedCredentials({
nodeEnv = process.env.NODE_ENV ?? "development",
adminEmail,
adminPassword,
seedCredentials = [],
}: SafeSeedCredentialOptions): void {
if (nodeEnv !== "production") {
return;
}
const credentials: SeedCredential[] = [{ label: "admin", email: adminEmail, password: adminPassword }, ...seedCredentials];
if (credentials.some((credential) => !credential.email?.trim() || !credential.password?.trim())) {
throw new Error("Refusing to run database seed in production with missing seed credentials.");
}
if (
credentials.some((credential) => (credential.email ? DEFAULT_SEED_EMAILS.has(credential.email) : false) || credential.password === DEFAULT_ADMIN_PASSWORD)
) {
throw new Error("Refusing to run database seed in production with default seed credentials.");
}
}
async function emitSeedDiagnostic(diagnostics: DbSeedDiagnostics | undefined, event: DbSeedDiagnosticEvent): Promise<void> {
await diagnostics?.(event);
}
export async function runDbSeed<TResult = void>({
nodeEnv = process.env.NODE_ENV ?? "development",
adminEmail,
adminPassword,
seedCredentials,
seed,
diagnostics,
}: RunDbSeedOptions<TResult>): Promise<TResult> {
assertSafeSeedCredentials({ nodeEnv, adminEmail, adminPassword, seedCredentials });
await emitSeedDiagnostic(diagnostics, { phase: "start", nodeEnv, adminEmail });
try {
const result = await seed();
await emitSeedDiagnostic(diagnostics, { phase: "success", nodeEnv, adminEmail });
return result;
} catch (error) {
await emitSeedDiagnostic(diagnostics, { phase: "failure", nodeEnv, adminEmail, error });
throw error;
}
}