Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL: Require at least one argument in a query

I have the following schema set up for my user query:

{
  type: UserType,
  args: {
    id: {
        type: GraphQLID,
        description: "A user's id.",
    },
    email: {
        type: GraphQLString,
        description: "A user's email.",
    },
},
resolve: async (parent, args) => {
  // ...
}

I want to accept both id and email as arguments, but at least one is required. Is there a way to set this up in the schema, without having to write extra code inside the resolve function?

Or would it be more advisable to create separate queries for each argument? For example: getUserById, getUserByEmail, getUserBySessionToken, etc?

like image 977
Norbert Avatar asked Jan 23 '18 13:01

Norbert


2 Answers

I think the easiest way using resolve function. But why do you think it will be messy?

try {
  if(!args.id && !args.email) {
    throw new Error('Specify id or email');
  }
  ...
} catch(e) {
  return Promise.reject(e);
}
like image 113
Talgat Saribayev Avatar answered Oct 15 '22 10:10

Talgat Saribayev


If you want a schema that enforces one and only one of the two, you could add an enum argument to qualify a single string argument. The schema might look like this in graphql:

type query {
  getUser(
    lookup: String!
    lookupType: UserLookupType!
  ): User
}

enum UserLookupType {
  ID
  EMAIL
}
like image 29
Aryeh Leib Taurog Avatar answered Oct 15 '22 10:10

Aryeh Leib Taurog