简体   繁体   中英

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?

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()
        }
    }
}

The above answer is correct, the usual approach is to add singular and plural form of queries. However, in large schema, this can duplicate a lot of logic and can be abstracted a little bit for example with Node interface and node, nodes queries. But the nodes query is usually applied with ids as argument (in Relay viz node Fields ), but you can build your own abstracted way for fetching so that you have just nodes with some argument for type and based on that you can say what type of list to fetch. However, the simpler approach is to just duplicate the logic for every type and use singular and plural form of query and do the same type of queries as above or in this code snippet for every type. For more detail explanation on implementing GraphQL list modifiers in queries or even as an input for mutations. I just published the article on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM