有没有办法将回调触发器添加到路由参数。快递文档 例如:
app.param('startDate', handleDateParameter);
我希望它仅适用于特定路线,例如api/reports/getDailyReports/:startDate
Nest 的概念Pipes
可能是您问题的答案。
您可以在路由中使用的控制器中的方法/路由级别(而不是全局/模块/控制器级别)使用@Param('name', YourCustomPipe)
它。
示例:
首先,定义您的自定义HandleDateParameter
管道:
// handle-date-parameter.pipe.ts
import { PipeTransform, Injectable, ArgumentMetadata, HttpStatus,
BadRequestException } from '@nestjs/common';
@Injectable()
export class HandleDateParameter implements PipeTransform<string, number> {
transform(value: string, metadata: ArgumentMetadata) {
// ...implement your custom logic here to validate your date for example or do whatever you want :)
// finally you might want to return your custom value or throw an exception (i.e: throw new BadRequestException('Validation failed'))
return myCustomValue;
}
}
然后在你的控制器中使用它:
// reports.controller.ts
// Make your imports here (HandleDateParameter and other stuff you need)
@Controller('reports')
export class ReportsController {
@Get('getDailyReports/:startDate')
// The following line is where the magic happens :) (you will handle the startDate param in your pipe
findDailyReports(@Param('startDate', HandleDateParameter) startDate: Date) {
//.... your custom logic here
return myResult;
}
}