forked from aws-amplify/aws-appsync-apollo-extensions-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppSyncInterceptor.swift
50 lines (41 loc) · 1.66 KB
/
AppSyncInterceptor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Apollo
import ApolloAPI
import Foundation
public class AppSyncInterceptor: ApolloInterceptor {
public var id: String = UUID().uuidString
let authorizer: AppSyncAuthorizer
public init(_ authorizer: AppSyncAuthorizer) {
self.authorizer = authorizer
}
public func interceptAsync<Operation>(chain: Apollo.RequestChain,
request: Apollo.HTTPRequest<Operation>,
response: Apollo.HTTPResponse<Operation>?,
completion: @escaping (Result<Apollo.GraphQLResult<Operation.Data>, Error>) -> Void) where Operation: ApolloAPI.GraphQLOperation
{
Task {
do {
request.addHeader(name: "User-Agent", value: await PackageInfo.userAgent)
try await retrieveHeadersAndAddToRequest(request)
chain.proceedAsync(
request: request,
response: response,
interceptor: self,
completion: completion)
} catch {
chain.handleErrorAsync(error, request: request, response: response, completion: completion)
}
}
}
func retrieveHeadersAndAddToRequest<Operation>(_ request: Apollo.HTTPRequest<Operation>) async throws {
let headers = try await authorizer.getHttpAuthorizationHeaders(request: request.toURLRequest())
for header in headers {
request.addHeader(name: header.key, value: header.value)
}
}
}