0
我正通过其官方website学习GraphQL。节点GraphQL解析来自API的空数据
我的graphql在这段代码上的用途是作为我现有的REST API的包装。 要做到这一点,我已经有这种反应的REST API:
GET: /people/:id
RESPONSE:
{
"person": [
{
"id": "1",
"userName": "mark1",
"firstName": "Mark",
"lastName": "Zuckerberg",
"email": "[email protected]",
"friends": [
"/people/2",
"/people/3"
]
}
]
}
,这下面的代码是我graphql模式
import {
GraphQLList,
GraphQLObjectType,
GraphQLString,
GraphQLSchema
} from "graphql";
import fetch from "node-fetch";
const BASE_URL = "http://localhost:5000";
function getPersonByURL(relativeUrl) {
return fetch(`${BASE_URL}${relativeUrl}`)
.then(res => res.json())
.then(json => json.person);
}
const PersonType = new GraphQLObjectType({
name: "Person",
type: "Somebody",
fields:() => ({
firstName: {
type: GraphQLString,
resolve: person => person.firstName
},
lastName: {
type: GraphQLString,
resolve: person => person.lastName
},
email: {
type: GraphQLString
},
id: {
type: GraphQLString
},
userName: {
type: GraphQLString
},
friends: {
type: new GraphQLList(PersonType),
resolve: (person) => person.friends.map(getPersonByURL)
}
})
});
const QueryType = new GraphQLObjectType({
name: "Query",
description: "the root of all queries",
fields:() => ({
person: {
type: PersonType,
args: {
id: { type: GraphQLString }
},
resolve: (root, args) => getPersonByURL(`/people/${args.id}`)
}
})
});
export default new GraphQLSchema({
query: QueryType
});
当我执行使用Graphiql
它返回的每个字段为空的请求。 我相信我犯了错误,我代表我的JSON响应或如何从休息API访问我的JSON响应。
这些请求,并从graphiql
REQUEST
{
person(id: "1") {
firstName
}
}
RESPONSE
{
"data": {
"person": {
"firstName": null
}
}
}
结果可以请你任何提示帮助吗?
是的,这就是答案,谢谢您的帮助 – lloistborn