用Nestjs Interceptor修改响应
我有用于修改图标路径的拦截器:
@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)
};
}),
);
}
}
当我在查找方法中使用它时,它可以正常工作并修改图标路径。
@UseInterceptors(GetProgramIconInterceptor)
async find(id: string): Promise<Application> {
const application = await this.repository.findById(id);
if (!application) throw new ApplicationNotFoundException();
return application;
}
当我将此拦截器用于Findall方法时,它无法正常工作,也不会修改路径。
@UseInterceptors(GetProgramIconInterceptor)
async findAll(): Promise<Application[]> {
return this.repository.find();
}
我知道Findall方法的结果是一个数组,我可以为其创建另一个拦截器。有什么方法可以用一个拦截器处理
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您正在处理存储库模型功能(
find
andfindbyid
)的承诺(并且尚不可观察到的)结果,因此,将管道输送到可观察到的时,这意味着您正在观察存储库
或repository []
附加A codesandbox 我创建了可能是单个对象或对象数组的资源的映射。
这里的魔术只是确保我们有条件表达式,何时资源为数组,
如果存储库模型的结果是可观察的,则必须使用rxjs中的
iif
表达式。Since you are working with promises (And not already observable) results from the repository model functions (
find
andfindById
) when piping into the observable it means you are observing overrepository
orrepository[]
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
If the results from the repository model were observables you had to use
iif
expressions from rxjs.