env.validation.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { plainToInstance } from 'class-transformer';
  2. import {
  3. IsString,
  4. IsUrl,
  5. IsInt,
  6. Min,
  7. Max,
  8. IsOptional,
  9. validateSync,
  10. IsEnum,
  11. IsNumber,
  12. IsBoolean,
  13. } from 'class-validator';
  14. enum NodeEnv {
  15. Development = 'development',
  16. Production = 'production',
  17. Test = 'test',
  18. }
  19. class EnvironmentVariables {
  20. @IsEnum(NodeEnv)
  21. @IsOptional()
  22. NODE_ENV: NodeEnv = NodeEnv.Development;
  23. // @IsString()
  24. // MYSQL_URL!: string;
  25. @IsString()
  26. MONGO_URL!: string;
  27. @IsString()
  28. JWT_SECRET!: string;
  29. @IsInt()
  30. @Min(60)
  31. @Max(86400)
  32. @IsOptional()
  33. JWT_EXPIRES_IN_SECONDS: number = 43200; // 12 hours
  34. @IsString()
  35. @IsOptional()
  36. ENCRYPTION_KEY?: string;
  37. @IsInt()
  38. @Min(1024)
  39. @Max(65535)
  40. @IsOptional()
  41. PORT: number = 3000;
  42. // ===== Redis Config =====
  43. @IsString()
  44. REDIS_HOST!: string;
  45. @IsNumber()
  46. REDIS_PORT!: number;
  47. @IsOptional()
  48. @IsString()
  49. REDIS_PASSWORD?: string; // empty string is allowed
  50. @IsOptional()
  51. @IsNumber()
  52. REDIS_DB?: number;
  53. @IsOptional()
  54. @IsString()
  55. REDIS_KEY_PREFIX?: string;
  56. // If you later add TLS:
  57. @IsOptional()
  58. @IsBoolean()
  59. REDIS_TLS?: boolean;
  60. }
  61. export function validateEnvironment(config: Record<string, unknown>) {
  62. const validatedConfig = plainToInstance(EnvironmentVariables, config, {
  63. enableImplicitConversion: true,
  64. });
  65. const errors = validateSync(validatedConfig, {
  66. skipMissingProperties: false,
  67. });
  68. if (errors.length > 0) {
  69. const messages = errors
  70. .map((error) => {
  71. const constraints = error.constraints;
  72. return constraints ? Object.values(constraints).join(', ') : '';
  73. })
  74. .filter(Boolean);
  75. throw new Error(`Environment validation failed:\n${messages.join('\n')}`);
  76. }
  77. return validatedConfig;
  78. }