nest 配置文件
John Doenest 配置文件
- Controller:传统意义上的控制器,提供 api
接口,负责处理路由、中转、验证等一些简洁的业务;
- Service:又称为 Provider, 是一系列服务、repo、工厂方法、helper
的总称,主要负责处理具体的业务,如数据库的增删改查、事务、并发等逻辑代码;
- Module:负责将 Controller 和 Service 连接起来,类似于 namespace
的概念;
配置文件
process.env.NODE_ENV是自定义的,需要配置, 安装
cross-env配置
修改 package.json里面的 scripts
1
| "scripts": { "start:dev": "cross-env NODE_ENV=development nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "cross-env NODE_ENV=production node dist/main",}
|
定义配置文件 这是我的目录
1 2 3 4 5
| src config --development.ts --production.ts --index.ts
|
1 2 3
| type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: '123456', database: 'blog', charset: 'utf8mb4', entities: [__dirname + '/db/**/*.entity{.js,.ts}'], synchronize: true, }, port: 3005,
|
1 2
| development: development,};const env = process.env.NODE_ENV;export default () => config[env];
|
1 2 3 4 5 6
| imports: [ ConfigModule.forRoot({ isGlobal: true, load: [config], }), TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => configService.get('db'), }), ArticleModule, ], controllers: [AppController], providers: [AppService],}) export class AppModule {}
|
在main.ts 中使用配置
核心 app.get(ConfigService)
1 2 3
| const app = await NestFactory.create(AppModule); const config = app.get(ConfigService); const globalPrefix = config.get('globalPrefix'); app.setGlobalPrefix(globalPrefix); app.useGlobalInterceptors(new TransformInterceptor()); bootStrap(app); const port = config.get('port'); await app.listen(port); console.log(`app running in ${port}`);} main();
|
1 2 3 4 5 6 7 8
| const options = new DocumentBuilder() .setTitle('Blog Api') .setDescription('The Blog Api Description') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, options); const swaggerPrefix = config.get('swaggerPrefix'); SwaggerModule.setup(swaggerPrefix, app, document);} export default function bootStrap(app: INestApplication) { const config = app.get(ConfigService); initSwagger(app, config);}
|