【发布时间】:2019-01-25 14:06:00
【问题描述】:
我正在将GraphQL 与REST 端点连接起来,我确认每当我调用http://localhost:3001/graphql 时,它都会点击REST 端点并且它正在返回JSON 对GraphQL 服务器的响应,但我得到了从GraphQL 服务器到GUI 的空响应如下:
{
"data": {
"merchant": {
"id": null
}
}
}
查询(手动解码):
http://localhost:3001/graphql?query={
merchant(id: 1) {
id
}
}
下面是我的GraphQLObjectType 的样子:
const MerchantType = new GraphQLObjectType({
name: 'Merchant',
description: 'Merchant details',
fields : () => ({
id : {
type: GraphQLString // ,
// resolve: merchant => merchant.id
},
email: {type: GraphQLString}, // same name as field in REST response, so resolver is not requested
mobile: {type: GraphQLString}
})
});
const QueryType = new GraphQLObjectType({
name: 'Query',
description: 'The root of all... queries',
fields: () => ({
merchant: {
type: merchant.MerchantType,
args: {
id: {type: new GraphQLNonNull(GraphQLID)},
},
resolve: (root, args) => rest.fetchResponseByURL(`merchant/${args.id}/`)
},
}),
});
来自REST 端点的响应(我也尝试使用 JSON 中的单个对象而不是 JSON 数组):
[
{
"merchant": {
"id": "1",
"email": "a@b.com",
"mobile": "1234567890"
}
}
]
使用node-fetch的REST调用
function fetchResponseByURL(relativeURL) {
return fetch(`${config.BASE_URL}${relativeURL}`, {
method: 'GET',
headers: {
Accept: 'application/json',
}
})
.then(response => {
if (response.ok) {
return response.json();
}
})
.catch(error => { console.log('request failed', error); });
}
const rest = {
fetchResponseByURL
}
export default rest
GitHub:https://github.com/vishrantgupta/graphql
JSON 端点(虚拟):https://api.myjson.com/bins/8lwqk
编辑:添加node.js标签,可能是promise对象的问题。
【问题讨论】:
-
来自 REST 端点的响应形状可能与您的架构不匹配。您能否更新您的问题以包含来自 REST 端点的完整响应?
-
感谢@DanielRearden 检查了这一点。我已经用端点响应更新了我的问题。
-
rest中的resolve: (root, args) => rest.fetchResponseByURL(merchant/${args.id}/)是什么? -
这是从其他 js 文件
export default rest导出的,这有一个 RESTfetchfetchResponseByURL方法 -
@xadm 我已经用这些细节更新了我的问题
标签: node.js express graphql express-graphql