refactor(config): add env parsing helpers and tighten startup validation
This commit is contained in:
66
src/common/config/env.utils.ts
Normal file
66
src/common/config/env.utils.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
export function parseBoolean(
|
||||
value: string | undefined,
|
||||
fallback: boolean,
|
||||
): boolean {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (['true', '1', 'yes', 'y', 'on'].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (['false', '0', 'no', 'n', 'off'].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function parsePositiveInteger(
|
||||
value: string | undefined,
|
||||
fallback: number,
|
||||
): number {
|
||||
if (!value) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
|
||||
export function parseCsvList(value: string | undefined): string[] {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return value
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item.length > 0);
|
||||
}
|
||||
|
||||
export function isLikelyHttpOrigin(origin: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(origin);
|
||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseRedisRequired(config: {
|
||||
nodeEnv?: string;
|
||||
redisRequired?: string;
|
||||
}): boolean {
|
||||
if (config.redisRequired === undefined) {
|
||||
return config.nodeEnv === 'production';
|
||||
}
|
||||
|
||||
return parseBoolean(config.redisRequired, false);
|
||||
}
|
||||
Reference in New Issue
Block a user