-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsightsClient.swift
69 lines (61 loc) · 2.34 KB
/
InsightsClient.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import AlgoliaFoundation
import Foundation
import Logging
/// Algolia Insights client
public class InsightsClient: Client {
/**
- Parameter appID: Algolia application ID.
- Parameter apiKey: Algolia API key of the application.
*/
public convenience init(appID: ApplicationID,
apiKey: APIKey,
region: Region? = nil,
extraUserAgents: [String] = []) {
let userAgents = [
"AlgoliaSDK-Insights/\(CurrentVersion.version) (\(OperatingSystem.description))"
] + extraUserAgents
let urlSessionConfiguration = URLSessionConfiguration.default
urlSessionConfiguration.httpAdditionalHeaders = [
"X-Algolia-Application-Id": appID.rawValue,
"X-Algolia-API-Key": apiKey.rawValue,
"User-Agent": userAgents.joined(separator: ";")
]
let urlSession = URLSession(configuration: urlSessionConfiguration)
let regionComponent = region.flatMap { ".\($0.rawValue)" } ?? ""
let hosts = [Host(url: "insights\(regionComponent).algolia.io")]
let transport = Transport(httpClient: urlSession,
hosts: hosts,
logger: Logger(label: "AlgoliaInsightsClient"))
let jsonEncoder = JSONEncoder()
jsonEncoder.dateEncodingStrategy = .algoliaClientDateEncodingStrategy
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .algoliaClientDateDecodingStrategy
self.init(transport: transport,
jsonEncoder: jsonEncoder,
jsonDecoder: jsonDecoder)
}
}
public extension InsightsClient {
/**
Send Insight event
- Parameter requestOptions: Configure request locally with RequestOptions
- Returns: JSON object
*/
func send(_ events: Event...) async throws {
try await send(events)
}
/**
Send Insights events
- Parameter requestOptions: Configure request locally with RequestOptions
- Returns: JSON object
*/
func send(_ events: [Event]) async throws {
let request = FieldWrapper.events(events)
let body = try jsonEncoder.encode(request)
try await transport.perform(method: .post,
path: "/1/events",
headers: ["Content-Type": "application/json"],
body: body,
requestType: .write)
}
}