如何在guard(ResourceOwnerGuard)之前执行管道(ValidateObjectId)?

时间:2019-04-14 12:39:57

标签: node.js mongoose server guard nestjs

我在玩nestjs和猫鼬。

代码:

class BrevesController {

    constructor(private readonly brevesService: BrevesService) { }
     // Here is used BreveOwnerGuard(1)
    @UseGuards(JwtAuthGuard, BreveOwnerGuard)
    @Get(':breveId')
    // Here is used ValidateObjectId(3)
    async getById(@Param('breveId', ValidateObjectId) id: string) {
        return await this.brevesService.getById(id)
    }
}

class BreveOwnerGuard {

    constructor(private readonly brevesService: BrevesService) { }

    async canActivate(context: ExecutionContext) {
        const req = context.switchToHttp().getRequest()
        const {user, params} = req
        const {breveId} = params
        // This is executed before ValidateObjectId in getById 
        // route handler and unknown error is thrown but we
        // have pipe for this.(2)
        const breve = await this.brevesService.getById(breveId)
        const breveCreatorId = breve.creatorId.toString()
        const userId = user.id
        return breveCreatorId === userId
    }
}

因此,在请求/ breves /:breveId具有无效对象ID之后,将在ValidateObjectId之前执行BreveOwnerGuard,并引发未知错误。

该流程是否有办法在BreveOwnerGuard之前验证ObjectId?

或者在这种情况下该怎么办?期望什么?

1 个答案:

答案 0 :(得分:0)

  

防护在每个中间件之后执行,但在任何拦截器或管道之前执行。

除了将ResourceOwnerGuard更改为管道或将ValidateObjectId更改为Guard之外,您无能为力。