ruby-on-rails 如何访问github graphql http header中的示例变量

2hh7jdfx  于 2023-03-31  发布在  Ruby
关注(0)|答案(1)|浏览(112)
class GithubGraphqlService
    URL = "https://api.github.com/graphql".freeze
    attr_reader :access_token
    
    def initialize(access_token)
        @access_token = access_token
    end

    def client
        http_adapter ||= GraphQL::Client::HTTP.new(URL) do
          def headers(_context)
            {
              "Authorization" => "Bearer #{access_token}",  //access_token is undefined
              "User-Agent" => "Ruby"
            }
          end
        end
    
        schema ||= GraphQL::Client.load_schema(http_adapter)
        @_client ||= GraphQL::Client.new(schema:, execute: http_adapter)
   end
end

我尝试了以下修复方法,但没有任何效果。
修复:1

def client
    http_adapter ||= GraphQL::Client::HTTP.new(URL) do
      def headers(_context)
        {
          "Authorization" => "Bearer #{@access_token}",  //@access_token is nil
          "User-Agent" => "Ruby"
        }
      end
    end

    schema ||= GraphQL::Client.load_schema(http_adapter)
    @_client ||= GraphQL::Client.new(schema:, execute: http_adapter)
end

修复:2例

def client
    github_access_token = @access_token
    http_adapter ||= GraphQL::Client::HTTP.new(URL) do
      def headers(_context)
        {
          "Authorization" => "Bearer #{github_access_token}",  //github_access_token is undefined
          "User-Agent" => "Ruby"
        }
      end
    end

    schema ||= GraphQL::Client.load_schema(http_adapter)
    @_client ||= GraphQL::Client.new(schema:, execute: http_adapter)
end

headers方法定义在GraphQL::Client::HTTP类的上下文中,这意味着它不能访问GithubGraphqlService类中定义的示例变量,包括@access_token

有没有办法访问header方法中的@access_token示例变量?
谢谢!

n3h0vuf2

n3h0vuf21#

因此,通过设计,他们希望您在query级别注入它
它看起来就像这样

# ...
def client
  http_adapter ||= GraphQL::Client::HTTP.new(URL) do
    def headers(context)
      access_token = context.fetch(:access_token)

      {
        "Authorization" => "Bearer #{access_token}",
        "User-Agent" => "Ruby"
      }
    end
  end

  schema ||= GraphQL::Client.load_schema(http_adapter)

  @_client ||= GraphQL::Client.new(schema:, execute: http_adapter)
end
# ...
client.query(query_definition, context: { access_token: '...' })

相关问题