I was using v0.33 and recently updated it to the latest version of Apollo SDK and facing an issue:
In version 0.33 we were using a protocol HTTPNetworkTransportPreflightDelegate
and its delegate methods were get called on every graphql calls and hence I add the latest token as headers in the calls-
class GraphQL: NSObject {
func networkTransport(_ networkTransport: HTTPNetworkTransport, shouldSend request: URLRequest) -> Bool {
return true
}
func networkTransport(_ networkTransport: HTTPNetworkTransport, willSend request: inout URLRequest) {
var headers = request.allHTTPHeaderFields ?? [String: String]()
headers["Authorization"] = "Bearer <token>"
headers["X-STATE"] = StaticClass.state
headers["X-GEO"] = ""
request.allHTTPHeaderFields = headers
}
}
And I was creating the Apollo client like this:
class GraphQL: NSObject {
lazy var networkTransport: HTTPNetworkTransport = {
let transport = HTTPNetworkTransport(url: URL(string: EndPoints.graphQLURL)!)
transport.delegate = self
return transport
}()
lazy var apollo = ApolloClient(networkTransport: self.networkTransport)
func performMutation() { ... }
// Other class methods below
}
Problem -
After updating it to the latest version the protocol has been removed and hence I can not add headers with latest token in every graphql calls. My token gets change every 20 min.
This is how I am using the code now:
class GraphQL: NSObject {
private(set) lazy var apollo: ApolloClient = {
let url = URL(string: EndPoints.graphQLURL)!
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = addHeaders() // Add your headers here
let client = URLSessionClient(sessionConfiguration: configuration)
let store = ApolloStore(cache: InMemoryNormalizedCache())
let provider = DefaultInterceptorProvider(client: client, store: store)
let networkTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)
return ApolloClient(networkTransport: networkTransport, store: store)
}()
func addHeaders() -> [AnyHashable: Any] {
var headers = [AnyHashable: Any]()
headers["Authorization"] = "Bearer <token>"
headers["X-STATE"] = StaticClass.state
headers["X-GEO"] = ""
return headers
}
func performMutation() { ... }
}
All my graphql methods including initialization and all are in a class name GraphQL and I am using a static var to call these methods:
class GlobalClass {
static var graphQL = GraphQL()
// Other stuff
}
Calling like this:
GlobalClass.graphQL.apollo.performMutation()
How can I add / update my token
as headers to the ApolloClient object for every call I make?