【问题标题】:Nestjs: Route ParameterNestjs:路由参数
【发布时间】:2021-10-03 18:27:01
【问题描述】:

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

app.param('startDate', handleDateParameter);

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

【问题讨论】:

    标签: express nestjs


    【解决方案1】:

    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;
        }
    }
    

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

    【讨论】:

    • 看起来很有希望,但我需要为每条路由调用管道吗(每次我在这个控制器中使用“startDate”参数)?
    • 是的,从我的角度来看,您必须使用此参数在每条路线上调用它。或者,如果您的控制器的每个路由都使用它,您可能希望在控制器级别使用它,如下所示:@Controller('reports') @UsePipes(HandleDateParameterPipe) export class ReportsController { @Get('getDailyReports/:startDate') { // ... 你在这里编码 } }
    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 2021-07-17
    • 2018-10-30
    • 2017-12-03
    • 2016-03-05
    • 1970-01-01
    • 2018-04-05
    • 2021-09-21
    相关资源
    最近更新 更多