Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify Request and Response coming from PUT using interceptor in NestJs

Tags:

nestjs

I am using NestJs. I am using intercepter in my controller for PUT request.

I want to change the request body before the PUT request and I want to change response body that returns by PUT request. How to achieve that?

Using in PUT

  @UseInterceptors(UpdateFlowInterceptor)
  @Put('flows')
  public updateFlow(@Body() flow: Flow): Observable<Flow> {
    return this.apiFactory.getApiService().updateFlow(flow).pipe(catchError(error =>
      of(new HttpException(error.message, 404))));
  }

Interceptor

@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
  public intercept(_context: ExecutionContext, next: CallHandler): Observable<FlowUI> {

    // how to change request also

    return next.handle().pipe(
      map(flow => {
        flow.name = 'changeing response body';
        return flow;
      }),
    );
  }
}
like image 383
kandarp Avatar asked Aug 29 '19 14:08

kandarp


1 Answers

I was able to do it by getting request from ExecutionContext following is the code.

@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
  public intercept(
    _context: ExecutionContext,
    next: CallHandler
  ): Observable<FlowUI> {

    // changing request
    let request = _context.switchToHttp().getRequest();
    if (request.body.name) {
      request.body.name = 'modify request';
    }

    return next.handle().pipe(
      map((flow) => {
        flow.name = 'changeing response body';
        return flow;
      })
    );
  }
}
like image 54
kandarp Avatar answered Nov 27 '22 09:11

kandarp