30 lines
917 B
TypeScript
30 lines
917 B
TypeScript
import { z } from 'zod';
|
|||
|
|
|
||
|
|
export const envSchema = z.object({
|
||
|
|
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
|
||
|
|
PORT: z.coerce.number().int().positive().default(3000),
|
||
|
|
// Orígenes permitidos por CORS, separados por coma. Vacío = mismo origen.
|
||
|
|
CORS_ORIGINS: z
|
||
|
|
.string()
|
||
|
|
.default('')
|
||
|
|
.transform((v) =>
|
||
|
|
v
|
||
|
|
.split(',')
|
||
|
|
.map((s) => s.trim())
|
||
|
|
.filter(Boolean),
|
||
|
|
),
|
||
|
|
LOG_LEVEL: z.enum(['error', 'warn', 'log', 'debug', 'verbose']).default('log'),
|
||
|
|
});
|
||
|
|
|
||
|
|
export type Env = z.infer<typeof envSchema>;
|
||
|
|
|
||
|
|
export function validateEnv(raw: Record<string, unknown>): Env {
|
||
|
|
const result = envSchema.safeParse(raw);
|
||
|
|
if (!result.success) {
|
||
|
|
const detail = result.error.issues
|
||
|
|
.map((i) => `${i.path.join('.')}: ${i.message}`)
|
||
|
|
.join('; ');
|
||
|
|
throw new Error(`Configuración inválida (.env): ${detail}`);
|
||
|
|
}
|
||
|
|
return result.data;
|
||
|
|
}
|