swiftgraphqlcodable

How can I create a Swift structure for handling GraphQL queries?


I am currently creating a structure for the graphql queries as follows

struct Payload: Codable {
   var query: String
   var variables: Patch
}

struct Patch: Codable {
  var id: ID
  var patch: [String: String]
} 

And this gets called like so

        let patches: [String: String] = [...]

        let mutation: String = "mutation ($id: ID!, $patch: ObjectPatch) {...}"

        let P1 = Patch(id: id, patch: patches)

        let payload = Payload(query: mutation, variables:P1)

        let postData = try! JSONEncoder().encode(payload)

How can I define the Payload structure such that I can assign any valid Codable object to the 'variables' property depending on what the query is?

struct Payload: Codable {
   var query: String
   var variables: any Codable?
}

struct Patch: Codable {
  var id: ID
  var patch: [String: String]
}

struct Vars1: Codable {
  var id: ID
  var name: String
}

Solution

  • This looks like a good situation to use generics for your Payload type.

    struct Payload<Parameters: Codable>: Codable {
       var query: String
       var variables: Parameters?
    }
    

    With this definition of Payload you can assign any type that conforms to Codable to the variables property

    let payload = Payload(query: mutation, variables: P1)
    let payload2 = Payload(query: mutation, variables: Vars1(id: UUID(), name: "foo"))
    let payload3 = Payload(query: mutation, variables: ["a": "...", "c": "1"])