首页 > 解决方案 > 如何在警卫(ResourceOwnerGuard)之前执行管道(ValidateObjectId)?

问题描述

我在玩 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 之后,BreveOwnerGuard 在 ValidateObjectId 之前执行并抛出未知错误。

这个流程有没有办法在 BreveOwnerGuard 之前验证 ObjectId ?

或者在这种情况下我应该怎么做?期望什么?

标签: node.jsmongooseserverguardnestjs

解决方案


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

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


推荐阅读