Fastify
对于网关系统来说,无论是资源还是API接口数据,它都将承担所有的请求转发。虽然外层可以有Nginx做负载均衡策略,但是如果框架本身的性能越好。业务效果的实现也就越好,同时对业务代码的要求也可以稍微降低一点。
而NEST作为一个上层框架,可以通过适配器模式让底层可以兼容任意类型HTTP类型的Node框架。本身内置的框架有Express和Fastify。
为了使用Fastify,你必须在Nest项目中安装Fastify。你就需要执行以下命令
cnpm install -D @nestjs/platform-fastify
然后再对main.ts做如下更改
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication
} from '@nestjs/platform-fastify'
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(3000);
}
bootstrap();
这样我们就将Fastify配置好了。
版本控制
我们如果做后台系统,就会存在版本更新换代的情况,比如说我们做一个物流系统,肯定会存在物料和用户两个模块。这两款系统作为基础应用,后期也会对其他的项目提供OpenAPI.同时也不能避免升级之后,需要兼容老项目的情况。这时就会存在多种版本的API。所以我们也要考虑到添加版本控制来避免未来项目升级的时候,造成系统崩溃的情况。
单个请求控制
第一步:在main.ts中启用版本控制
import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication
} from '@nestjs/platform-fastify'
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
// Interface version controls
app.enableVersioning({
type: VersioningType.URI
})
await app.listen(3000);
}
bootstrap();
第二步:启用版本控制之后在Controller中请求方法添加对应的版本号装饰器。
import {Controller,Version} from '@nestjs/common';
@Version('1')
getHello():string{
return "Hello World"
}
封装返回对象
自定义配置文件
虽然Nest自带了环境配置的功能,使用dotenv来作为默认解析。但是默认配置看起来并不是十分的清爽,我们接下来使用YAML来覆盖默认配置
- 在使用自定义YAML文件之前,我们要先修改app.module.ts中ConfigModule的配置项ignoreEnvFile,禁用默认读取.env的规则
ConigModule.forRoot({ignoreEnvFile:ture})
- 然后再安装yaml的node库
cnpm install yaml
- 安装完毕之后。在根目录新建
.config文件夹,并创建对应环境的yaml文件。如下图所示:
4.新建utils/index.ts文件,添加读取yaml文件的方法:
import { parse } from 'yaml'
const path = require('path');
const fs = require('fs');
// 获取项目运行环境
export const getEnv = () => {
return process.env.RUNNING_ENV
}
// 读取项目配置
export const getConfig = () => {
const environment = getEnv()
const yamlPath = path.join(process.cwd(), `./.config/.${environment}.yaml`)
const file = fs.readFileSync(yamlPath, 'utf8')
const config = parse(file)
return config
}
- 最后在
app.module.ts中自定义配置项就可以正常使用环境变量。
@Module({
imports: [
ConfigModule.forRoot({
ignoreEnvFile: true,
isGlobal: true,
load: [getConfig]
}), UserModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
使用自定义配置
完成之前的配置之后,就可以使用cross-env指定运行环境来使用配置变量。
- 添加cross-env依赖:
cnpm install cross-env
- 修改启动命令:
"start:dev": "cross-env RUNNING_ENV=dev nest start --watch",
- 添加.dev.yaml配置
TEST_VALUE:
name: cookie
- 在我们之前创建好的UserController里面添加ConfigService以及新的需求:
export class UserController {
constructor(
private readonly userService: UserService,
private readonly configService: ConfigService
) { }
@Get('getTestName')
getTestName() {
return this.configService.get('TEST_VALUE').name;
}
}
- 完成以上步骤之后,我们接下来访问http://localhost:3000/v1/user/getTestName 就能够看到已经根据环境拿到了对应的值。