【问题标题】:GraphQL Apollo iOS Client Response HeadersGraphQL Apollo iOS 客户端响应标头
【发布时间】:2018-02-14 14:49:51
【问题描述】:

我正在使用 Apollo iOS 客户端进行 GraphQL 查询。我需要在标头中传递 Auth 令牌,我可以使用下面的代码来实现 -

let apolloAuth: ApolloClient = {
            let configuration = URLSessionConfiguration.default
            let token = "Bearer \(UserDefaults.standard.string(forKey: "UserToken") ?? "")"
            // Add additional headers as needed
            configuration.httpAdditionalHeaders = ["Authorization": token]

            let url = URL(string: "...URL.../graphql")!

            return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))
        }()

我的获取查询如下 -

apolloAuth.fetch(query: referralQuery){ (result, error) in

        if let error = error {
            print(error.localizedDescription)
            return
        }else{
            self.referralId = result?.data?.referrals?.id
        }

    }

现在我的服务器在作为响应标头的一部分的每个请求之后返回一个刷新的身份验证令牌。我需要从响应标头中获取令牌,但我无法找到一种方法来做到这一点。有人可以指导我吗?

【问题讨论】:

    标签: ios swift3 graphql apollo


    【解决方案1】:

    URLSessionConfiguration 对象带有一个共享的 HTTPCookieStorage 单例对象。使用该配置设置 apollo 客户端后,您可以使用服务器将身份验证令牌存储在 cookie 中,然后在每次请求时将 cookie 发送到客户端。自动地,您将能够像这样访问该 cookie:

    apollo.fetch(query: GraphQLQuery()) { result, error in
            if let error = error { fatalError(error.localizedDescription) }
            if let data = result?.data {
              // do something with data
            }
            self.getCookies()
          }
    
    func getCookies() {
        let cookies = HTTPCookieStorage.shared.cookies
        if let c = cookies {
          print(c)
          // if your server sent a token inside a cookie, you will see it here
        }
      }
    

    【讨论】:

      【解决方案2】:

      使用拦截器从响应头中读取标记。

      示例代码:

      class UserManagementInterceptor: ApolloInterceptor {
      
          /// Helper function to add the token then move on to the next step
          private func addTokenAndProceed<Operation: GraphQLOperation>(
              to request: HTTPRequest<Operation>,
              chain: RequestChain,
              response: HTTPResponse<Operation>?,
              completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
                  
                  if let headerFields = response?.httpResponse.allHeaderFields {
                      // Read the required tokens
                  }
                  
                  chain.proceedAsync(request: request,
                                     response: response,
                                     completion: completion)
              }
          
          func interceptAsync<Operation: GraphQLOperation>(
              chain: RequestChain,
              request: HTTPRequest<Operation>,
              response: HTTPResponse<Operation>?,
              completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
              addTokenAndProceed(to: request,
                                 chain: chain,
                                 response: response,
                                 completion: completion)
              
          }
      }
      

      参考:Creating a client

      【讨论】:

        猜你喜欢
        • 2019-07-26
        • 2019-07-01
        • 2020-06-29
        • 2020-07-22
        • 2020-06-14
        • 2019-06-22
        • 2019-06-19
        • 2019-07-26
        • 2019-05-22
        相关资源
        最近更新 更多