一覧へ戻る
alxevvv/nest-zod-config(新しいタブで開きます)
主要言語: TypeScript
Define NestJS configuration with validation and type safety using zod
- star 数
- 5
- watcher 数
- 1
- fork 数
- 0
- issue 数
- 1
- 最終更新
- 2023/11/01
主要言語: TypeScript
Define NestJS configuration with validation and type safety using zod
Define NestJS configuration with validation and type safety using zod
npm install zod nest-zod-config
If you want to load configuration from .env file, also install
dotenv package:
npm install dotenv
# .env port=3000 str=something
// app.config.ts import { Config } from 'nest-zod-config'; import { z } from 'zod'; const appConfigSchema = z.object({ port: z.number(), str: z.string(), }); export class AppConfig extends Config(appConfigSchema) {}
// app.service.ts import { Injectable } from '@nestjs/common'; import { AppConfig } from './app.config'; @Injectable() export class AppService { constructor(private readonly config: AppConfig) {} someMethod() { // `this.config` now contains your configuration with types: // { port: 3000, str: 'something' } } }
// app.module.ts import { ZodConfigModule, dotEnvLoader } from 'nest-zod-config'; import { AppConfig } from './app.config'; import { AppService } from './app.service'; @Module({ imports: [ ZodConfigModule.forRootAsync({ config: AppConfig, loader: dotEnvLoader(), }), ], providers: [AppService], }) export class AppModule {}
For example in the bootstrap function before application creation:
// main.ts import { NestFactory } from '@nestjs/core'; import { dotEnvLoader, loadConfig } from 'nest-zod-config'; import { AppModule } from './app.module'; import { AppConfig } from './app.config'; async function bootstrap() { const config = await loadConfig(AppConfig, dotEnvLoader()); const app = await NestFactory.create(AppModule); await app.listen(config.PORT); } bootstrap();
Licensed under the MIT license. Copyright (c) 2023-present Vladislav Alexeev