summaryrefslogtreecommitdiff
path: root/Hutch/Networking/GraphQLRequest.swift
blob: bce7b4073b84dd3f41009aa95592426ceaaa38fe (plain) (blame)
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
import Foundation

/// The JSON body sent with every GraphQL request.
struct GraphQLRequestBody: Encodable, Sendable {
    let query: String
    let variables: [String: AnyCodable]?
}

/// The top-level shape of every GraphQL response.
struct GraphQLResponse<T: Decodable>: Decodable {
    let data: T?
    let errors: [GraphQLError]?
}

// MARK: - AnyCodable

/// A type-erased `Codable` wrapper so callers can pass `[String: Any]` variables
/// without losing type information at the encoding boundary.
struct AnyCodable: Sendable, Encodable {
    let value: any Sendable

    init(_ value: any Sendable) {
        self.value = value
    }

    func encode(to encoder: any Encoder) throws {
        var container = encoder.singleValueContainer()
        switch value {
        case let v as String:
            try container.encode(v)
        case let v as Int:
            try container.encode(v)
        case let v as Double:
            try container.encode(v)
        case let v as Bool:
            try container.encode(v)
        case let v as [any Sendable]:
            try container.encode(v.map { AnyCodable($0) })
        case let v as [String: any Sendable]:
            try container.encode(v.mapValues { AnyCodable($0) })
        default:
            try container.encodeNil()
        }
    }
}