【问题标题】:Generic service, understanding if I am in GRAPHQL context or HTTP context?通用服务,了解我是在 GRAPHQL 上下文还是 HTTP 上下文中?
【发布时间】:2019-09-18 00:48:44
【问题描述】:

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

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

return this.request.headers["test"]

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

但我需要了解我在哪个上下文中才能返回正确的对象

有什么想法吗?

提前致谢

【问题讨论】:

    标签: javascript node.js typescript graphql nestjs


    【解决方案1】:

    你可以创建一个辅助函数来检索标题:

    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`);
      }
    }
    

    【讨论】:

    • 谢谢,应该可以,我只是想知道框架中是否有什么东西可以告诉我们——我们所处的环境。不过这可行——非常感谢
    猜你喜欢
    • 2019-04-10
    • 2020-04-05
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多