GraphiQL Returning null Values When Fetching All Records [duplicate]

限于喜欢 提交于 2019-12-08 03:28:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!