Andre Baltieri
Andre Baltieri

Reputation: 435

NestJs - How to get request body on interceptors

I need to get the request body on my interceptor, before it goes to my controller:

import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
        // How can I get the request body here?
        // Need to be BEFORE the Controller exec
    }
}

Upvotes: 15

Views: 20632

Answers (2)

Serhii
Serhii

Reputation: 7543

If your interceptor is for rest endpoints I think Kim Kern completely covered this part in his answer.

There are additional possibilities to use interceptor and controllers. For example controller can be an entry point for your micro service for example listening a kafka messages (or any different ones):

@Controller()
export class DemoConsumerController {
  private readonly logger = new Logger(DemoConsumerController.name);

  @UseInterceptors(LogInterceptor)
  @EventPattern('demo-topic')
  async listenToKafkaMessage (
    @Payload() payload,
    @Ctx() context: KafkaContext,
  ) {
    this.logger.debug(`payload: ${payload}`)
    this.logger.verbose(`Topic: ${context.getTopic()}`);
    this.logger.verbose(`KafkaContext: ${JSON.stringify(context)}`);
  }
}

In this case to get body, or better to say message you need a little modification:

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const value = context.switchToHttp().getRequest().value

        // default rest part of code
        return next.handle()
    }

So to avoid of misunderstanding you can verify your request to figureOut what the value contains your payload:

console.log('getRequest: ', context.switchToHttp().getRequest())
// or 
console.log('context: ', context)

Upvotes: 0

Kim Kern
Kim Kern

Reputation: 60347

In your interceptor you can do:

async intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
    const body = context.switchToHttp().getRequest().body;
    // e.g. throw an exception if property is missing

Alternatively, you can use middleware where you directly have access to the request:

(req, res, next) => {

Upvotes: 23

Related Questions