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

NestJS如何用单个拦截器兼容单对象与数组响应的字段修改

问题原因

你当前的拦截器逻辑默认接口返回值为单个Application普通对象,直接对顶层返回值做展开、替换icon字段的操作。当findAll接口返回数组类型结果时,顶层返回值是Array实例,本身不存在icon属性,数组内的每个实体元素完全没被处理,自然无法生效。

兼容单对象/数组的拦截器实现

只需要在拦截器的映射逻辑里加一层类型判断,针对数组、单对象两种返回结构分别处理即可,不需要编写两个单独的拦截器:

@Injectable()
export class GetProgramIconInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        return next.handle().pipe(
            map(data => {
                // 兼容空返回值场景,避免运行报错
                if (!data) return data;

                // 数组场景:遍历每一项替换icon路径
                if (Array.isArray(data)) {
                    return data.map(item => {
                        if (!item) return item;
                        return {
                            ...item,
                            icon: generalFUnctions.getApplicationIcon(item.icon)
                        }
                    })
                }

                // 单个对象场景:沿用原有处理逻辑
                return {
                    ...data,
                    icon: generalFUnctions.getApplicationIcon(data.icon)
                };
            }),
        );
    }
}
扩展说明

如果后续接口返回分页结构(比如格式为{ list: Application[], total: number, page: number }),只需要在判断分支里追加对应逻辑,处理data.list数组即可,同一个拦截器可以覆盖所有返回Application实体的场景。

内容的提问来源于stack exchange,提问作者paranoid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:30:43