首页 > 解决方案 > 如何使用 NestJs 中的拦截器修改来自 PUT 的请求和响应

问题描述

我正在使用 NestJs。我在我的控制器中使用拦截器来处理 PUT 请求。

我想在 PUT 请求之前更改请求正文,并且我想更改 PUT 请求返回的响应正文。如何做到这一点?

在 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))));
  }

拦截器

@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;
      }),
    );
  }
}

标签: nestjs

解决方案


我能够通过以下代码来做到这request一点ExecutionContext

@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;
      }),
    );
  }
}

推荐阅读