GraphiQL Returning null Values When Fetching All Records [duplicate]
Asked Answered
C

1

1

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

Countrified answered 14/2, 2018 at 11:45 Comment(0)
L
4

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),
Lunatic answered 14/2, 2018 at 12:54 Comment(2)
Oh of course! Thankyou so much.Countrified
thank you! I'm so dumb, didn't understand why such a simple query wasn't working. Now it makes sense, cheersStomacher

© 2022 - 2024 — McMap. All rights reserved.