Search code examples
graphqlreasonbucklescript

Decoding Json/Reading Errors in ReasonML


I have got an graphql query coming back from aws's appsync service. This is the json that comes back from the query.

https://github.com/idkjs/reason-apollo-question/blob/600584c454ffb2efd08b8e42e3adca0eb151ba60/scratch/persons.json#L1-L27

    {
  "data": {
    "listPeople": {
      "items": [
        {
          "age": 23,
          "id": "123",
          "name": "BobTest",
          "__typename": "Person"
        },
        {
          "age": 24,
          "id": "124",
          "name": "JoeTest",
          "__typename": "Person"
        },
        {
          "age": 25,
          "id": "125",
          "name": "JimTest",
          "__typename": "Person"
        }
      ],
      "__typename": "PersonConnection"
    }
  }
}

This is what it looks like logged to the console. enter image description here

This is the query response in apollo-dev-tools: enter image description here

Error accessing items array.

Trying to log the items values to console by running https://github.com/idkjs/reason-apollo-question/blob/d38e7fbc33f02ab718c7227958d88f02adba1696/src/Persons.re#L66-L70

| Data(response) =>
               Js.log(response##listPeople);
               let listPeople = response##listPeople;
               let items = response##listPeople##items;
Js.log(items);

produces this error:

      We've found a bug for you!
  /Users/prisc_000/code/REASON/APOLLO/reason-apollo-question/src/Persons.re 69:32-51

  67 ┆ Js.log(response##listPeople);
  68 ┆ let listPeople = response##listPeople;
  69 ┆ let items = response##listPeople##items;
  70 ┆ Js.log(items);
  71 ┆

  This has type:
    option({. "items": option(Js.Array.t(option(
      {. "age": int, "id": string, "name":  string})))
      })

   But somewhere wanted:
    Js.t('a)

    ninja: build stopped: subcommand failed.
    >>>> Finish compiling(exit: 1)

How do I resolve this type error?

Thank you!


Solution

  • Solution:

    https://github.com/idkjs/reason-apollo-question/blob/2924b1eb928cf0e4de57d5659c5da1bed4dd981c/src/Persons.re#L31-L33

    Basically, i had not groked Some/None variables yet.

    When you see the compiler telling you its looking for an option as noted in the error above, you have get the value, if it exists, by wrapping the value in Some.

    So this:

    let name = item##name;
    let id = item##id;
    let age = item##age;
    

    Had to be changed to this:

    let name = Some(item##name);
    let id = Some(item##id);
    let age = Some(item##age);
    

    That's it.