Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL List or single object

I got the following "problem". I am used to having an API like that.

/users
/users/{id}

The first one returns a list of users. The second just a single object. I would like the same with GraphQL but seem to fail. I got the following Schema

var schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      users: {
        type: new GraphQLList(userType),
        args: {
          id: {type: GraphQLString}
        },
        resolve: function (_, args) {
          if (args.id) {
            return UserService.findOne(args.id).then(user => [user]);
          } else {
            return UserService.find()
          }
        }
      }
    }
  })
});

How can I modify the type of users to either return a List OR a single object?

like image 970
Daniel Avatar asked Sep 21 '16 07:09

Daniel


Video Answer


1 Answers

You shouldn't use one field for different purposes. Instead of that, make two fields. One for single object and another for list of objects. It's better practice and better for testing

fields: {
    user: {
        type: userType,
        description: 'Returns a single user',
        args: {
            id: {type: GraphQLString}
        },
        resolve: function (_, args) {
            return UserService.findOne(args.id);
        }
    },
    users: {
        type: new GraphQLList(userType),
        description: 'Returns a list of users',
        resolve: function () {
            return UserService.find()
        }
    }
}
like image 93
LordDave Avatar answered Oct 13 '22 00:10

LordDave