最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - GraphQL: Require at least one argument in a query - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question edited Jan 23, 2018 at 13:35 Norbert asked Jan 23, 2018 at 13:30 NorbertNorbert 2,7718 gold badges57 silver badges113 bronze badges 1
  • Related question: Making Graphql input where input can take different types; the comments there point to a @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
Add a comment  | 

2 Answers 2

Reset to default 9

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
}

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);
}
发布评论

评论列表(0)

  1. 暂无评论