在解析器中将数组映射到架构

时间:2018-10-10 08:48:35

标签: javascript reactjs graphql

使用GraphQL,我有以下启动板,可以毫无问题地获得单个对象的结果:

https://launchpad.graphql.com/xqnxw308xl

但是,当我尝试应用相同的概念但返回所有“字符”的数组时,我收到错误消息:

"Expected Iterable, but did not find one for field Query.getCharacters."

https://launchpad.graphql.com/qxm0m79xpp

在解析程序中,我想了解如何将API返回的“字符”数组映射到我的模式。

1 个答案:

答案 0 :(得分:0)

您正在调用的API的响应如下:

{
    "count": 87, 
    "next": "https://swapi.co/api/people/?page=2", 
    "previous": null, 
    "results": [
        {
            "name": "Luke Skywalker", 
            "height": "172", 
            "mass": "77", 
        },
    ]
}

这是您从解析器返回的对象,如错误所示,它不是Iterable,因此GraphQL不知道如何处理它。您需要先转换API结果,然后再返回,如下所示:

const resolvers = {
  Query: {
    getCharacters: () => {
      return fetch('https://swapi.co/api/people')
        .then(res => res.json())
        .then(json => json.results);
    }
  },
  Character: {
    // transform specific fields here
  }
}

请注意,name字段的解析器不再需要,因为该字段的名称与Character解析器返回的每个getCharacters对象的属性名称匹配。

相关问题