Nestjs:路线参数

时间:2018-05-23 18:06:47

标签: express nestjs

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

app.param('startDate', handleDateParameter);

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

1 个答案:

答案 0 :(得分:1)

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

您可以在路线中使用@Param('<your-param>' 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 <your-custom-value>;
  }
}

然后在你的控制器中使用它

// 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 <whatever-need-to-be-returned>;
    }
}


如果有帮助,请告诉我;)