Search code examples
javascriptapiguardnestjs

Nestjs apply function to each controller function/routes after validation has done


my controller:

    @Post('route1')
    @HttpCode(202)
    fun1(@Body() req: reqModel) {
        this.service1.findAll()  
        //do smth
        return true;
    }

    @Post('route2')
    @HttpCode(202)
    fun2(@Body() req: reqModel) {
        this.service1.findAll()  
        //do smth
        return true;
    }

I am trying to achieve the following mechanism:

1- validation has passed because I have model and class-validator in the models

2- now I want to call a service to get some data in each function in this controller this service check smth and then throw an exception or return true

I tried to use Guard @UseGuards(guradclass) but the guards works before the class validator

how can I achieve that


Solution

  • The execution order is the following if that can help you

    • Middleware
    • Guards
    • Interceptors (before the stream is manipulated)
    • Pipes
    • Interceptors (after the stream is manipulated)
    • Exception filters (if any exception is caught)