我正在通过他们的官方website学习GraphQL。
我的graphql对此代码的目的是作为现有REST API的包装器。 要做到这一点,我已经有了这个回复的休息api:
<img src="http://localhost/wp/wp-content/uploads/2017/05/IMG_0061-300x225.jpg" alt="garden image" width="300" height="225" class="alignnone size-medium wp-image-386916" />
以下代码是我的graphql架构
GET: /people/:id
RESPONSE:
{
"person": [
{
"id": "1",
"userName": "mark1",
"firstName": "Mark",
"lastName": "Zuckerberg",
"email": "mark@facebook.com",
"friends": [
"/people/2",
"/people/3"
]
}
]
}
当我使用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
});
执行请求时,它在每个字段上返回null。
我相信我在如何表示我的json响应或如何从rest api访问我的json响应时犯了错误。
这些是来自Graphiql
graphiql
你能帮忙解决一下吗?
答案 0 :(得分:1)
要找到问题,我已将你的json放在gist上并修改你的代码如下:
// ...
firstName: {
type: GraphQLString,
resolve: person => JSON.stringify(person)
},
// ...
运行以下查询后:
{
person(id: "1") {
firstName
}
}
结果如下:
{
"data": {
"person": {
"firstName": "[{\"id\":\"1\",\"userName\":\"mark1\",\"firstName\":\"Mark\",\"lastName\":\"Zuckerberg\",\"email\":\"mark@facebook.com\",\"friends\":[\"/people/2\",\"/people/3\"]}]"
}
}
}
您可以注意到person
数组,所以很明显它没有firstName
和其他属性。您必须在每个字段解析程序或根类型解析程序中解包数组:
resolve: (root, args) => getPersonByURL(`/people${args.id}.json`)
.then(persons => persons[0])
这是带有工作代码的GraphQL Launchpad:https://launchpad.graphql.com/j1v0kprrp