How to create a GraphQL response from json?

Hi,
I have a saved json response of GetCustomersQuery and I’d like to instantiante the GetCustomersQuery.Data using that saved file. It is described in the docs but when I do it, I get the exception JSONDecodingError.missingValue

My local json structure is

{
  "data": {
    "customers_customers": [
      {
        "__typename": "customers_customers",
        "customer_id": "047eb02e-d28e-45a7-bafa-998e42ff3ae1"
      },
      {
        "__typename": "customers_customers",
        "customer_id": "442ef309-c3d1-4f4c-9b87-79783245188e"
      }
     ]
}

let jsonObject = try JSONSerialization.jsonObject(with: data) as! [String: AnyHashable]
do {
    let result = try GetCustomersQuery.Data(data: jsonObject, variables: [:])
    print(result.customers_customers)
} catch {
    print(error)
}

I see that MyQuery.Data also have other initializer such as public init(_dataDict: DataDict)

Is this the correct way of doing it?

ps: I’m aware thast Apollo also provides the generated mocks but want I want to test if an actual network response decodes as expected.

thanks!

So my mistake was that the json root element was the data key. The json need to contain directly the type of the data. So in this case


{
    "customers_customers": [
      {
        "__typename": "customers_customers",
        "customer_id": "047eb02e-d28e-45a7-bafa-998e42ff3ae1"
      },
      {
        "__typename": "customers_customers",
        "customer_id": "442ef309-c3d1-4f4c-9b87-79783245188e"
      }
}

Then the initializer using the data works:

let result = try GetCustomersQuery.Data(data: jsonObject, variables: [:])
print(result.customers_customers)
1 Like