How to execute pipe(ValidateObjectId) before guard(ResourceOwnerGuard)?
Asked Answered
W

1

3

Im playing around with nestjs and mongoose.

The code:

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

So after request /breves/:breveId with invalid object id, the BreveOwnerGuard is executed before ValidateObjectId and unknown error is thrown.

Is there a way for this flow to validate the ObjectId before BreveOwnerGuard ?

Or what should I do in this case? What is expected ?

Worldling answered 14/4, 2019 at 12:39 Comment(0)
C
3

Guards are executed after each middleware, but before any interceptor or pipe.

Not much you can do other than change the ResourceOwnerGuard to a pipe or the ValidateObjectId into a Guard.

Cuba answered 17/7, 2019 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.