简体   繁体   English

Nest.js 中的嵌套拦截器

[英]Nested interceptors in Nest.js

How to implement a nested interceptor in Nest.js?如何在 Nest.js 中实现嵌套拦截器?

I have two interceptors: UsersInterceptor and PostsInterceptor我有两个拦截器: UsersInterceptorPostsInterceptor

UsersInterceptor:用户拦截器:

@Injectable()
export class UsersInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(map(data => ({
      id: data._id,
      email: data.email,
      createdAt: data.createdAt
    })));
  }
}

PostsInterceptor:帖子拦截器:

@Injectable()
export class PostsInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(map(data => ({
      id: data._id,
      title: data.title,
      content: data.content,
      user: {}, // I want the UsersInterceptor result here. I have the user's data in data.user
      createdAt: data.createdAt
    })));
  }
}

Now, I want to put the UserInterceptor 's result into the user object in the PostsInterceptor when I use it.现在,我想在使用时将UserInterceptor的结果放入PostsInterceptoruser对象中。

As described in the request lifecycle docs , interceptors work on the incoming request in the order they are bound, and on the outgoing response in the inverse order they are bound. 如请求生命周期文档中所述,拦截器按绑定顺序处理传入请求,并按绑定顺序处理传出响应。 This means that if you bind your interceptors like @UseInterceptors(PostInterceptor, UserInterceptor) then you should be able to see UserInterceptor 's return in the PostInterceptor这意味着,如果您绑定像@UseInterceptors(PostInterceptor, UserInterceptor)这样的拦截器@UseInterceptors(PostInterceptor, UserInterceptor)那么您应该能够在PostInterceptor看到UserInterceptor的返回

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

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