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 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?
2 Answers
Reset to default 9If 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
}
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);
}
@oneOf
RFC which will be a nice answer to this question but I think isn't rolled out yet? – user56reinstatemonica8 Commented Dec 14, 2023 at 11:04