You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用NestJS拦截器仅修改请求体的部分字段?

解决方案

修改后的geoloc.interceptor.ts代码如下:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, from, lastValueFrom } from 'rxjs';
import { map } from 'rxjs/operators';
const NodeGeocoder = require('node-geocoder');

const options = {
  provider: "opendatafrance",
};
const geocoder = NodeGeocoder(options);

@Injectable()
export class GeoLocInterceptor implements NestInterceptor {
  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest();
    const body = request.body;
    
    // 仅当请求体包含address字段时才执行地理编码逻辑
    if (!body?.address) {
      return next.handle();
    }

    const monaddress = body.address;
    const geocodeResult = from(geocoder.geocode(monaddress));
    const geocoded = await lastValueFrom(geocodeResult);

    // 保留原请求体所有字段,按需添加地理编码结果(若控制器无需此数据可删除该行)
    request.body = {
      ...body,
      geocoded: geocoded
    };

    // 在响应中追加地理编码结果,同时保留原响应内容
    return next.handle().pipe(
      map(value => ({
        ...value,
        geoCoder: geocoded
      }))
    );
  }
}

关键修改说明:

  • 保留原请求体字段:通过扩展运算符...body展开原请求体,避免丢失其他字段,同时按需添加地理编码结果,无需硬编码字段名。
  • 通用复用性:增加if (!body?.address)判断,无address字段的请求直接跳过处理,确保拦截器能安全应用在任意路由上。
  • 代码规范优化:将类名改为大驼峰GeoLocInterceptor,变量声明替换为const/let,符合TypeScript编码规范。

若控制器不需要用到地理编码后的geocoded数据,可直接删除request.body = {...body, geocoded: geocoded};这一行,仅保留响应中的结果即可。

内容的提问来源于stack exchange,提问作者Philippe Corrèges

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:33:25