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?
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);
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With