57 lines
1.1 KiB
TypeScript
57 lines
1.1 KiB
TypeScript
import { plainToInstance } from 'class-transformer';
|
|
import {
|
|
IsNotEmpty,
|
|
IsOptional,
|
|
IsString,
|
|
validateSync,
|
|
} from 'class-validator';
|
|
|
|
class EnvironmentVariables {
|
|
@IsNotEmpty({ message: 'DATABASE_URL is required for database connection' })
|
|
@IsString()
|
|
DATABASE_URL: string;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
NODE_ENV?: string = 'development';
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
PORT?: string = '4001';
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
JWT_ACCESS_SECRET?: string;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
JWT_REFRESH_SECRET?: string;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
REDIS_HOST?: string;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
REDIS_PORT?: string;
|
|
}
|
|
|
|
export function validateEnv(config: Record<string, unknown>) {
|
|
const validatedConfig = plainToInstance(EnvironmentVariables, config, {
|
|
enableImplicitConversion: true,
|
|
});
|
|
|
|
const errors = validateSync(validatedConfig, {
|
|
skipMissingProperties: false,
|
|
});
|
|
|
|
if (errors.length > 0) {
|
|
const messages = errors
|
|
.map((err) => Object.values(err.constraints || {}).join(', '))
|
|
.join('; ');
|
|
throw new Error(`Environment Validation Error: ${messages}`);
|
|
}
|
|
|
|
return validatedConfig;
|
|
}
|