问题
I am trying to build a simple GraphQL schema. I have an json-server endpoint running on localhost which returns some simple json data.
I can return a user when supplying an id. The query to do this in the schema looks like this:
staff: {
type: StaffType,
args: { id: { type: GraphQLInt }},
resolve(parentValue, { id }) {
return axios.get(`http://localhost:3000/staff/${id}`)
.then(resp => resp.data);
}
}
The GraphQL query looks like this:
{
staff(id: 1){
id
Name
}
}
and it returns this in the GraphiQL client:
{
"data": {
"staff": {
"id": 1,
"Name": "John Doe"
}
}
}
My problem starts when I try to return all users. I created another query to try to just fetch everything from http://localhost:3000/staff
with no args passed in. If I go directly to this url in the browser it returns all users as expected. If I try it via GraphiQL, however, it seems to return an object, but all the fields are null. There is no error given either in GraphiQL or on the console. Code examples below:
The query in the schema
allStaff: {
type: StaffType,
resolve(parentValue, args) {
return axios.get(`http://localhost:3000/staff/`)
.then(resp => resp.data);
}
}
The GraphiQL query
{
allStaff {
id
Name
}
}
The result I'm getting
{
"data": {
"allStaff": {
"id": null,
"Name": null,
}
}
}
if I console log resp.data there is data being returned and, as I say, the endpoint returns data when I access it directly via the browser exactly as expected.
Have I missed something?
Thanks
回答1:
The JSON data may be an array of user objects, but GraphQL is still expecting just the one. That's because in your schema, you've defined the return type for allStaff
as StaffType
. You need to wrap it with the List wrapper, like this:
type: new GraphQLList(StaffType),
来源:https://stackoverflow.com/questions/48786430/graphiql-returning-null-values-when-fetching-all-records