34 lines
860 B
TypeScript
34 lines
860 B
TypeScript
import 'dotenv/config';
|
|
|
|
export class MissingEnvironmentError extends Error {
|
|
readonly code = 'MISSING_ENVIRONMENT_VARIABLE';
|
|
|
|
constructor(readonly variableName: string) {
|
|
super(`Missing required environment variable: ${variableName}`);
|
|
this.name = 'MissingEnvironmentError';
|
|
}
|
|
}
|
|
|
|
export function requireEnv(
|
|
name: string,
|
|
env: NodeJS.ProcessEnv = process.env,
|
|
): string {
|
|
const value = env[name]?.trim();
|
|
if (!value) throw new MissingEnvironmentError(name);
|
|
return value;
|
|
}
|
|
|
|
export function envPort(
|
|
name: string,
|
|
fallback: number,
|
|
env: NodeJS.ProcessEnv = process.env,
|
|
): number {
|
|
const raw = env[name]?.trim();
|
|
if (!raw) return fallback;
|
|
const value = Number(raw);
|
|
if (!Number.isInteger(value) || value < 1 || value > 65535) {
|
|
throw new Error(`Invalid port in environment variable: ${name}`);
|
|
}
|
|
return value;
|
|
}
|