【发布时间】:2017-10-28 06:52:51
【问题描述】:
我正在通过他们的官方website学习GraphQL。
我在此代码上的 graphql 的目的是作为我现有 REST API 的包装器。 为此,我已经有了一个带有此响应的 rest api:
GET: /people/:id
RESPONSE:
{
"person": [
{
"id": "1",
"userName": "mark1",
"firstName": "Mark",
"lastName": "Zuckerberg",
"email": "mark@facebook.com",
"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 执行请求时,它在每个字段上返回 null。
我相信我在如何表示我的 json 响应或如何从 rest api 访问我的 json 响应时犯了错误。
这些是来自graphiql的请求和结果
REQUEST
{
person(id: "1") {
firstName
}
}
RESPONSE
{
"data": {
"person": {
"firstName": null
}
}
}
你能帮忙提示一下吗?
【问题讨论】:
标签: json node.js rest graphql relay