【问题标题】:Mapping array to schema in resolver将数组映射到解析器中的模式
【发布时间】:2018-10-10 20:23:54
【问题描述】:

使用 GraphQL,我有以下 Launchpad,我可以在其中毫无问题地获取单个对象的结果:

https://launchpad.graphql.com/xqnxw308xl

但是,当我尝试应用相同的概念,而是返回一个包含所有“字符”的数组时,我收到了错误:

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

https://launchpad.graphql.com/qxm0m79xpp

在解析器中,我想了解如何将从 API 返回的“字符”数组映射到我的架构。

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:

    您调用的 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 字段的解析器,因为该字段的名称与 getCharacters 解析器返回的每个 Character 对象的属性名称相匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 2019-11-04
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多