这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战
模块
模块是具有 @Module() 装饰器的类。 @Module() 装饰器提供了元数据,Nest 用它来组织应用程序结构。
@module() 装饰器接受一个描述模块属性的对象:
providers | 由 Nest 注入器实例化的提供者,并且可以至少在整个模块中共享 |
---|---|
controllers | 必须创建的一组控制器 |
imports | 导入模块的列表,这些模块导出了此模块中所需提供者 |
exports | 由本模块提供并应在其他模块中可用的提供者的子集。 |
中间件
中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,以及应用程序请求响应周期中的 next() 中间件函数。 next() 中间件函数通常由名为 next 的变量表示。
Nest 中间件实际上等价于 express 中间件。 下面是Express官方文档中所述的中间件功能:
中间件函数可以执行以下任务:
- 执行任何代码。
- 对请求和响应对象进行更改。
- 结束请求-响应周期。
- 调用堆栈中的下一个中间件函数。
- 如果当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间件函数。否则, 请求将被挂起。
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request...');
next();
}
}
复制代码
应用中间件
中间件不能在 @Module() 装饰器中列出。我们必须使用模块类的 configure() 方法来设置它们。包含中间件的模块必须实现 NestModule 接口。我们将 LoggerMiddleware 设置在 ApplicationModule 层上。
app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('cats');
}
}
复制代码
必须设置forRoutes, 星号(*)是匹配所有,或者指定对应的模块
可以使用对象的方式来配置{ path: 'cats', method: RequestMethod.GET },只对get方法生效
还能用通配符,'ab*cd'
函数中间件
export function logger(req, res, next) {
console.log(`Request...`);
next();
};
复制代码
多中间件
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
复制代码
全局中间件
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);
复制代码
管道
- 转换:管道将输入数据转换为所需的数据输出
- 验证:对输入数据进行验证,如果验证成功继续传递; 验证失败则抛出异常;
用的是class-validator 和 class-transformer 这两个库 需要我们手动安装这两个库
内置管道
- ValidationPipe:验证数据,需要使用class-validator的验证器
例如
export class CreateCatDto {
@IsString()
@IsNotEmpty()
@Type(() => String)
readonly name: string;
@IsNumber()
@IsNotEmpty()
@Type(() => Number)
readonly age: number
@IsString()
@IsNotEmpty()
@Type(() => String)
readonly breed: string
@Type(() => Boolean)
readonly isHot: boolean = false
}
复制代码
使用方式
@Post()
async create(@Body(new ValidationPipe(options)) createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
return '新增成功1111'
}
复制代码
- ParseIntPipe:把参数转换成int类型
@Get(':id')
async findOne(@Param('id', new ParseIntPipe()) id) {
return await this.catsService.findOne(id);
}
复制代码
-
ParseBoolPipe:转成boolean,使用方法同上
-
ParseArrayPipe:转成array
-
ParseUUIDPipe:它用来分析验证字符串是否是 UUID.