| 1 | import type { ZodDto } from './zod-dto.util' |
| 2 | import { resolve } from 'node:path' |
| 3 | import { program } from 'commander' |
| 4 | import { fileLoader, selectConfig as nestSelectConfig, TypedConfigModule } from 'nest-typed-config' |
| 5 | import { z } from 'zod' |
| 6 | import { zodValidate } from './zod-validate.util' |
| 7 | |
| 8 | export function selectConfig< |
| 9 | TOutput = unknown, |
| 10 | TInput = TOutput, |
| 11 | >(config: ZodDto<TOutput, TInput>): TOutput & { meta: { configPath: string } } { |
| 12 | const configPath = resolve( |
| 13 | process.cwd(), |
| 14 | program |
| 15 | .requiredOption('-c --config <config>', 'config path') |
| 16 | .parse(process.argv) |
| 17 | .opts()['config'], |
| 18 | ) |
| 19 | const module = TypedConfigModule.forRoot({ |
| 20 | schema: config, |
| 21 | validate(value) { |
| 22 | return zodValidate<TOutput, TInput>(value as TInput, config, (error) => { |
| 23 | return new Error(`Configuration is not valid:\n${z.prettifyError(error)}\n`) |
| 24 | }) as Record<string, unknown> |
| 25 | }, |
| 26 | load: fileLoader({ |
| 27 | absolutePath: configPath, |
| 28 | }), |
| 29 | }) |
| 30 | const selectedConfig = nestSelectConfig(module, config) |
| 31 | Object.defineProperty(selectedConfig, 'meta', { |
| 32 | value: { configPath }, |
| 33 | enumerable: false, |
| 34 | configurable: false, |
| 35 | writable: false, |
| 36 | }) |
| 37 | return selectedConfig as TOutput & { meta: { configPath: string } } |
| 38 | } |
| 39 |