Nestjs:路由参数

Nestjs: Route Parameter

有没有办法给路由参数添加回调触发器。 Express Documentation 例如:

app.param('startDate', handleDateParameter);

我希望它只适用于特定路线,例如 api/reports/getDailyReports/:startDate

Nest 的 Pipes 概念可能是您问题的答案。

您可以在您的控制器中使用 method/route 级别(相对于 global/module/controller 级别)在您的路线中使用 @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;
    }
}

让我知道它是否对您有帮助;)