Skip to content

Commit

Permalink
feat: add config validation
Browse files Browse the repository at this point in the history
Signed-off-by: ayman <aymanshaik1015@gmail.com>
  • Loading branch information
Nesopie committed Apr 29, 2024
1 parent bcadc9c commit 934092d
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/configuration.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
IsBoolean,
IsDefined,
IsInt,
IsNotEmpty,
IsString,
Max,
Min,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';

class DbConfig {
@IsNotEmpty()
@IsString()
host: string;

@IsInt()
@Min(0)
@Max(65535)
port: number;

@IsNotEmpty()
@IsString()
username: string;

@IsNotEmpty()
@IsString()
password: string;

@IsNotEmpty()
@IsString()
databaseName: string;

@IsBoolean()
synchronize: boolean;
}

export class Config {
@IsDefined()
@ValidateNested()
@Type(() => DbConfig)
db: DbConfig;
}
16 changes: 16 additions & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { join } from 'path';
import { readFileSync } from 'fs';
import { load } from 'js-yaml';
import { camelToSnakeCase } from '@/common/common';
import { Config } from '@/configuration.model';
import { validateSync } from 'class-validator';
import { plainToClass } from 'class-transformer';

const getConfigFilePath = () => {
switch (process.env.NODE_ENV) {
Expand Down Expand Up @@ -40,5 +43,18 @@ export default () => {
any
>;
mergeEnvVariablesRecursive(config);

const validateConfig = plainToClass(Config, config, {
enableImplicitConversion: true,
});

const errors = validateSync(validateConfig, {
skipMissingProperties: true,
});

if (errors.length > 0) {
throw new Error(errors.toString());
}

return config;
};

0 comments on commit 934092d

Please sign in to comment.