Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / GrandSlam / GrandSlamClient.swift

GrandSlamClient.swift49 lines · 1.7 KiBRaw
1//
2// GrandSlamClient.swift
3// XKit
4//
5// Created by Kabir Oberai on 19/11/19.
6// Copyright © 2019 Kabir Oberai. All rights reserved.
7//
8
9import Foundation
10import Dependencies
11
12struct GrandSlamClient: Sendable {
13
14 private let encoder = PropertyListEncoder()
15
16 private let lookupManager = GrandSlamLookupManager()
17
18 @Dependency(\.anisetteDataProvider) var anisetteDataProvider
19 @Dependency(\.httpClient) var httpClient
20
21 init() {}
22
23 func send<R: GrandSlamRequest>(_ request: R) async throws -> R.Decoder.Value {
24 let anisetteData = try await anisetteDataProvider.fetchAnisetteData()
25 let url = try await lookupManager.fetchURL(forEndpoint: R.endpoint)
26
27 let content = request.content(anisetteData: anisetteData)
28 var httpRequest = HTTPRequest(method: content.httpMethod, url: url)
29 httpRequest.headerFields[.contentType] = "text/x-xml-plist"
30 httpRequest.headerFields[.init(DeviceInfo.clientInfoKey)!] = anisetteData.deviceInfo.clientInfo
31 let body: Data? = switch content {
32 case .get:
33 nil
34 case .data(let body, _, .xml):
35 try PropertyListSerialization.data(
36 fromPropertyList: body, format: .xml, options: 0
37 )
38 case .data(let body, _, .json):
39 try JSONSerialization.data(withJSONObject: body)
40 }
41 request.configure(request: &httpRequest, anisetteData: anisetteData)
42
43 // GrandSlam doesn't seem to like reused (keep-alive) connections so create a
44 // new one for each request. cf https://github.com/rileytestut/AltSign/pull/52
45 let resp = try await httpClient.makeRequest(httpRequest, body: body, ephemeral: true)
46 return try R.Decoder.decode(data: resp.body)
47 }
48
49}