【问题标题】:Nested interceptors in Nest.jsNest.js 中的嵌套拦截器
【发布时间】:2020-12-28 02:48:43
【问题描述】:

如何在 Nest.js 中实现嵌套拦截器?

我有两个拦截器: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
    })));
  }
}

现在,我想在使用时将UserInterceptor 的结果放入PostsInterceptor 中的user 对象中。

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    As described in the request lifecycle docs,拦截器按照它们被绑定的顺序处理传入的请求,并以它们绑定的相反顺序处理传出的响应。这意味着如果你绑定像@UseInterceptors(PostInterceptor, UserInterceptor) 这样的拦截器,那么你应该能够在PostInterceptor 中看到UserInterceptor 的返回

    【讨论】:

    • 我怎样才能告诉PostsInterceptorUsersInterceptor 加载user 对象?
    • 应该在返回的data中。只要UserInterceptor将其添加到返回的数据中,它就会在那里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2021-04-27
    • 2015-11-22
    相关资源
    最近更新 更多