首页 > 解决方案 > 通用服务,了解我是在 GRAPHQL 上下文还是 HTTP 上下文中?

问题描述

有什么我可以注入来了解我所处的上下文,即我的服务是从 graphql 请求或 http 请求中调用的。

我有一个请求范围服务,需要返回一个标头。标头存储在REQUEST对象上,如果它是 HTTP 上下文,或者它在 graphql 上下文中可用(如我之前设置的那样),则可以自动注入该对象 - 因此

return this.request.headers["test"]

或者

return this.context.request.headers["test"]

但我需要了解我所处的上下文以返回正确的对象

有任何想法吗?

提前致谢

标签: javascriptnode.jstypescriptgraphqlnestjs

解决方案


您可以创建一个辅助函数来检索标头:

getHeader(key: string) {
  if (this.request && this.request.headers && this.request.headers[key]) {
    return this.request.headers[key];
  } else if (this.context.request && this.context.request.headers && this.context.request.headers[key]) {
    return this.context.request.headers[key];
  } else {
    throw new BadRequestException(`Required header ${key} is missing`);
  }
}

推荐阅读