如何从 REST Api 响应组成 graphQL 查询?
How to compose a graphQL query from a REST Api response?
我有一个来自 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")
}
`;
1st:您需要 name
和 address
道具(内部)people
查询 - 'ask for what you need' - 以获得结果。
第二步:使用 apollo-link-rest
通常需要 type patching - technique used to adapt/transform existing (REST) responses to the current needs (structures). It can be combined with response transformer,但不需要此步骤。
有时您需要为嵌套类型添加id
(从其他字段计算,唯一)(apollo 规范化缓存要求)或在desired/required 类型之上定义额外的'response type' - google 用于类型修补示例(f.e。patchDeeper
用法)或教程...定义修补程序,使用调试器...
当您知道 expect/what 需要什么时,事情就容易多了 - 将响应与有效的 graphql 响应进行比较。
有同样的问题,您可以在link中使用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
]
我有一个来自 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")
}
`;
1st:您需要 name
和 address
道具(内部)people
查询 - 'ask for what you need' - 以获得结果。
第二步:使用 apollo-link-rest
通常需要 type patching - technique used to adapt/transform existing (REST) responses to the current needs (structures). It can be combined with response transformer,但不需要此步骤。
有时您需要为嵌套类型添加id
(从其他字段计算,唯一)(apollo 规范化缓存要求)或在desired/required 类型之上定义额外的'response type' - google 用于类型修补示例(f.e。patchDeeper
用法)或教程...定义修补程序,使用调试器...
当您知道 expect/what 需要什么时,事情就容易多了 - 将响应与有效的 graphql 响应进行比较。
有同样的问题,您可以在link中使用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
]