diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 9b16ed0..4a6f78b 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -1,4 +1,41 @@ +import type { LoggerService } from '@services/logger.service'; import { injectable } from 'inversify'; +import { Env } from 'src'; @injectable() -export class CosmosConfig {} +export class CosmosConfig { + constructor(private readonly loggerService: LoggerService) {} + + /** + * Get env variables + */ + public get(value: string): T { + const envValue = process.env[value]; + + if (envValue === 'true') { + return true as T; + } + + if (envValue === 'false') { + return false as T; + } + + if (!Number.isNaN(Number(envValue))) { + return Number(envValue) as T; + } + + return envValue as T; + } + + /** + * Validate if env key exist and then return it + */ + public getEnvKey(key: string) { + const envKey = Env.EnvKeys[key]; + if (envKey) { + return envKey; + } else { + void this.loggerService.pino.warn(`${key} does not exist in you'r environnement`); + } + } +} diff --git a/packages/core/src/env/env.ts b/packages/core/src/env/env.ts index 20fcc59..14f79d7 100644 --- a/packages/core/src/env/env.ts +++ b/packages/core/src/env/env.ts @@ -1,15 +1,33 @@ import { injectable } from 'inversify'; import z, { type SafeParseError, type ZodError } from 'zod'; -// Fixes the return error from the Zod library. + +/** + * Fixes the return error from the Zod library. + */ function hashError(safeParseReturn: any): safeParseReturn is SafeParseError> { return safeParseReturn?.error; } @injectable() export class Env { + /** + * Access to zod library + */ public static validator = z; + /** + * Mapping of env key + */ + public static EnvKeys: { [key: string]: any } = {}; + + /** + * Process and validate env variables + */ public process(variables: { [key: string]: any }) { + for (const [envVariable, enValues] of Object.entries(variables)) { + Env.EnvKeys[envVariable] = envVariable; + } + const schema = z.object(variables); const parsed = schema.safeParse(process.env);