简体   繁体   English

使用nestjs拦截器修改响应

[英]Modify response with nestjs interceptor

I have Interceptor for modify icon path like this:我有拦截器来修改图标路径,如下所示:

@Injectable()
export class GetProgramIconInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        return next.handle().pipe(
            map(data => {
                return {
                    ...data,
                    icon: generalFUnctions.getApplicationIcon(data.icon)
                };
            }),
        );
    }
}

and when I use this in my find method, it works correctly and modifies the icon path.当我在我的 find 方法中使用它时,它可以正常工作并修改图标路径。

@UseInterceptors(GetProgramIconInterceptor)
async find(id: string): Promise<Application> {
    const application = await this.repository.findById(id);
     if (!application) throw new ApplicationNotFoundException();
     return application;
}

and when I use this Interceptor to the findAll method it doesn't work correctly and doesn't modify the path.当我将此拦截器用于 findAll 方法时,它无法正常工作并且不会修改路径。

@UseInterceptors(GetProgramIconInterceptor)
async findAll(): Promise<Application[]> {
     return this.repository.find();
}

I know the result of the findAll method is an array and I can create another Interceptor for it.我知道 findAll 方法的结果是一个数组,我可以为它创建另一个拦截器。 Is there any way to handle it with one Interceptor有没有办法用一个拦截器来处理它

Since you are working with promises (And not already observable) results from the repository model functions ( find and findById ) when piping into the observable it means you are observing over repository or repository[]由于您正在处理来自存储库模型函数( findfindById )的承诺(并且还不是可观察的)结果,当管道进入可观察对象时,这意味着您正在观察repositoryrepository[]

Attaching a codesandbox of an example i have created mapping over resource that is possibly single object or array of objects. 附上一个示例的代码框,我已经创建了可能是单个对象或对象数组的资源的映射。

The magic here is just making sure we have a conditional expression for when the resource is array or not这里的神奇之处在于确保我们有一个条件表达式来判断资源是否为数组

map((repositoryOrRespositories) => {
  if (Array.isArray(repositoryOrRespositories)) {
    return item.map((repository) => ({
      ...repository,
      icon: generalFUnctions.getApplicationIcon(repository.icon)
    }));
  } else {
    return { ...repositoryOrRespositories, icon: generalFUnctions.getApplicationIcon(repositoryOrRespositories.icon) };
  }
})

If the results from the repository model were observables you had to use iif expressions from rxjs.如果存储库模型的结果是可观察的,则必须使用 rxjs 中的iif表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM