在ReasonML中解码Json /读错误

时间:2018-05-29 09:22:34

标签: graphql reason bucklescript

我有一个来自aws的appsync服务的graphql查询。 这是从查询中返回的json。

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"
    }
  }
}

这就是它登录到控制台的样子。 enter image description here

这是apollo-dev-tools中的查询响应: enter image description here

访问items数组时出错。

尝试通过运行将items值记录到控制台 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);

产生此错误:

      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)

如何解决此类错误?

谢谢!

2 个答案:

答案 0 :(得分:2)

您似乎将response##listPeople定义为一个选项,因此您无法直接在其上调用response##listPeople##items。在阅读response##listPeople之前,您应该对items进行模式匹配。

答案 1 :(得分:1)

解决方案:

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

基本上,我还没有弄过Some / None变量。

当您看到编译器告诉您正在寻找上述错误中所述的选项时,您可以通过将值包装在Some中来获取值(如果存在)。

所以这个:

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

不得不改为:

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

那就是它。