1

any solution for pass authentication header in apollo graphQl(iOS) i have no idea for how can i pass header with requested url. i tried like this:

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")!)
}

does anyone help me?

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Check this answer https://stackoverflow.com/questions/55395589/how-to-add-header-in-apollo-graphql-ios – Ned Jul 20 '20 at 12:17
  • 1
    Also this will be helpful https://github.com/apollographql/apollo-ios/blob/main/docs/source/initialization.md. Check `HTTPNetworkTransportDelegate` – Ned Jul 20 '20 at 13:01

1 Answers1

2
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)
    }
}
Renish Dadhaniya
  • 10,642
  • 2
  • 31
  • 56