krz/hutch

an ios client for sourcehut

clone: git clone https://gitbay.org/krz/hutch.git

v2.15.0: Hutch/Networking/GraphQLRequest.swift · raw

 1import Foundation
 2
 3/// The JSON body sent with every GraphQL request.
 4struct GraphQLRequestBody: Encodable, Sendable {
 5    let query: String
 6    let variables: [String: AnyCodable]?
 7}
 8
 9/// The top-level shape of every GraphQL response.
10struct GraphQLResponse<T: Decodable>: Decodable {
11    let data: T?
12    let errors: [GraphQLError]?
13}
14
15// MARK: - AnyCodable
16
17/// A type-erased `Codable` wrapper so callers can pass `[String: Any]` variables
18/// without losing type information at the encoding boundary.
19struct AnyCodable: Sendable, Encodable {
20    let value: any Sendable
21
22    init(_ value: any Sendable) {
23        self.value = value
24    }
25
26    func encode(to encoder: any Encoder) throws {
27        var container = encoder.singleValueContainer()
28        switch value {
29        case let v as String:
30            try container.encode(v)
31        case let v as Int:
32            try container.encode(v)
33        case let v as Double:
34            try container.encode(v)
35        case let v as Bool:
36            try container.encode(v)
37        case let v as [String?]:
38            try container.encode(v)
39        case let v as [any Sendable]:
40            try container.encode(v.map { AnyCodable($0) })
41        case let v as [String: any Sendable]:
42            try container.encode(v.mapValues { AnyCodable($0) })
43        default:
44            try container.encodeNil()
45        }
46    }
47}