【问题标题】:How to compose a graphQL query from a REST Api response?如何从 REST Api 响应组成 graphQL 查询?
【发布时间】:2019-09-11 02:44:16
【问题描述】:

我有一个来自 REST API 服务器的 API 响应,我使用我的 REACT + Apollo 和 apollo-link-rest 调用它。但是 API 的响应看起来像这样

[
 [
   {
    "name": "joe"
    "address": "123 street hello city"
   },
   {
    "name": "joe2"
    "address": "1233 street2 hello2 city"
   }
 ],
 2356
]

如何使用这种响应创建一个查询,该查询具有一个数组,其中一个数字作为数组中的最后一项,并且数组的第一项由用户列表组成?

到目前为止,我只有这个查询。

const QueryTest = gql`
  query people {
    people @rest(type: "People", path: "/allpersons")
  }
`;

【问题讨论】:

标签: reactjs rest graphql apollo


【解决方案1】:

第一个:您需要在(内部)people 查询中使用 nameaddress 道具 - '询问你需要什么' - 以获得结果。

第二个:使用apollo-link-rest 通常需要type patching - 用于调整/转换现有(REST)响应以适应当前需求(结构)的技术。可以与response transformer结合使用,但这一步不是必须的。

有时您需要为嵌套类型(apollo 规范化缓存要求)添加 id(从其他字段计算,唯一)或在所需/必需类型之上定义其他“响应类型” - google 用于类型修补示例(fe @987654328 @用法)或教程...定义修补程序,使用调试器...

当您知道预期/需要什么时,这会容易得多 - 将响应与有效的 graphql 响应进行比较。

【讨论】:

    【解决方案2】:

    遇到同样的问题,您可以在链接中使用responseTransformer 来转换响应。

    const restLink = new RestLink({
        uri: '...',
        responseTransformer: async response =>
            response.json()
                  .then((data: any) => {
                    if (Array.isArray(data)) return { data }
                    else return data
                })
    });
    

    所以你应该能够像这样使用查询:

    const QueryTest = gql`
      query people {
        people @rest(type: "People", path: "/allpersons") {
          data
        }
      }
    `;
    

    data 将包含:

    [
     [
       {
        "name": "joe"
        "address": "123 street hello city"
       },
       {
        "name": "joe2"
        "address": "1233 street2 hello2 city"
       }
     ],
     2356
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2022-12-02
      • 2018-07-14
      • 2019-12-07
      • 2019-05-02
      • 1970-01-01
      • 2020-01-12
      • 2018-06-18
      • 2016-01-14
      相关资源
      最近更新 更多