graphql-client icon indicating copy to clipboard operation
graphql-client copied to clipboard

How to dynamically change headers

Open dfritsch86 opened this issue 5 years ago • 3 comments

I need to dynamically change the request headers. How to accomplish this?

dfritsch86 avatar Apr 23 '19 17:04 dfritsch86

You need to instantiate a new client each time you want to change the headers.

j-collier avatar Apr 26 '19 04:04 j-collier

Or use the context that you pass into the headers method.

require "graphql/client"
require "graphql/client/http"

# Star Wars API example wrapper
module SWAPI
  # Configure GraphQL endpoint using the basic HTTP network adapter.
  HTTP = GraphQL::Client::HTTP.new("https://example.com/graphql") do
    def headers(context)
      { "X-Api-Key" => context[:api_key] }
    end
  end  
end

And when you perform a query on your GraphQL client, pass in the context:

storefront_api_key = "dynamic api key"
result = SWAPI::Client.query(SWAPI::MyQuery, variables: {}, context: {api_key: storefront_api_key})

So everytime you perform a query, you have the opportunity to pass in a context to alter your headers.

tolgap avatar Jun 19 '19 09:06 tolgap

I really think this issue can be closed. The @tolgap solution works well

Nittarab avatar Sep 01 '21 18:09 Nittarab