【问题标题】:SwiftUI :how to add authentication header in apollo graphQl(iOS) with swift?SwiftUI:如何使用 swift 在 apollo graphQl(iOS) 中添加身份验证标头?
【发布时间】:2020-07-05 20:48:29
【问题描述】:

在 apollo graphQl(iOS) 中通过身份验证标头的任何解决方案 我不知道如何通过请求的 url 传递标头。 我试过这样:

import Apollo

class Network {
    static let shared = Network()
    let accessToken = "token-KEY"

    private(set) lazy var apollo = ApolloClient(url: URL(string: "http://localhost:1337/graphql")!)
}

有人帮我吗?

【问题讨论】:

标签: ios xcode graphql apollo


【解决方案1】:
class Network {
  static let shared = Network()
  
    private(set) lazy var apollo: ApolloClient = {
        let client = URLSessionClient()
        let cache = InMemoryNormalizedCache()
        let store = ApolloStore(cache: cache)
        let provider = NetworkInterceptorProvider(client: client, store: store)
        let url = URL(string: ENDPOINT_URL)!
        let transport = RequestChainNetworkTransport(interceptorProvider: provider,
                                                     endpointURL: url)
        return ApolloClient(networkTransport: transport)
    }()
}

class NetworkInterceptorProvider: LegacyInterceptorProvider {
    override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
        var interceptors = super.interceptors(for: operation)
        interceptors.insert(CustomInterceptor(), at: 0)
        return interceptors
    }
}

class CustomInterceptor: ApolloInterceptor {
    
    func interceptAsync<Operation: GraphQLOperation>(
        chain: RequestChain,
        request: HTTPRequest<Operation>,
        response: HTTPResponse<Operation>?,
        completion: @escaping (Swift.Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
        request.addHeader(name: "Authorization", value: TOKEN_VALUE)
        
        print("request :\(request)")
        print("response :\(String(describing: response))")

        chain.proceedAsync(request: request,
                           response: response,
                           completion: completion)
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 2019-08-09
    • 2018-06-22
    • 2018-08-18
    • 2019-08-19
    • 2021-07-22
    • 2017-08-06
    • 2018-05-23
    相关资源
    最近更新 更多