Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

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 method = request.method(anisetteData: anisetteData)
28 var httpRequest = HTTPRequest(method: method.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 method {
32 case .get:
33 nil
34 case .post(let body):
35 try PropertyListSerialization.data(
36 fromPropertyList: body, format: .xml, options: 0
37 )
38 }
39 request.configure(request: &httpRequest, anisetteData: anisetteData)
40
41 // GrandSlam doesn't seem to like reused (keep-alive) connections so create a
42 // new one for each request. cf https://github.com/rileytestut/AltSign/pull/52
43 let resp = try await httpClient.withEphemeralClient {
44 try await $0.makeRequest(httpRequest, body: body)
45 }
46 return try R.Decoder.decode(data: resp.body)
47 }
48
49}