简体   繁体   English

我可以在 GraphQL 请求标头中设置默认上下文吗?

[英]Can I set a default context in an GraphQL request header?

I am writing an app that makes a lot of API calls to the same GraphQL endpoint.我正在编写一个应用程序,它对同一个 GraphQL 端点进行大量 API 调用。 Most us the same authorization header, but a few require a different access token.大多数我们使用相同的授权标头,但少数需要不同的访问令牌。 In researching the problem, it looks like I can use header context to address this, but the issue is I only want to set up the endpoint once, so as soon as I load the schema it crashes because the context hasn't been set yet.在研究这个问题时,看起来我可以使用标头上下文来解决这个问题,但问题是我只想设置一次端点,所以一旦我加载架构它就会崩溃,因为尚未设置上下文.

HTTP = GraphQL::Client::HTTP.new("https://example.com") do
    def headers(context)
      {"Authorization": context[:access_token]}
    end
  end
 # code breaks at below line because context hasn't been set
  SCHEMA = GraphQL::Client.load_schema(HTTP)

I want to be able to set some default value like {"Authorization": context[:master_token]=ENV.fetch(MASTER_TOKEN)}我希望能够设置一些默认值,如{"Authorization": context[:master_token]=ENV.fetch(MASTER_TOKEN)}

Does anyone know how I can do this?有谁知道我怎么能做到这一点?

Figured it out.弄清楚了。

Turns out doing a simple conditional assignment does the trick.结果证明做一个简单的条件赋值就可以了。

{"Authorization": context[:token] ||= ENV.fetch(MASTER_TOKEN)}

So if context[:token] is nil , it will default to the MASTER_TOKEN因此,如果context[:token]nil ,它将默认为MASTER_TOKEN

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

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