How do I set up GraphQL query so one or another argument is required, but not both

心已入冬 提交于 2020-05-23 09:51:05

问题


I'm just getting to grips with GraphQL,

I have set up the following query: ​

type: UserType,
args: {
    id:    { name: 'id',    type: new GraphQLNonNull(GraphQLID)     },
    email: { name: 'email', type: new GraphQLNonNull(GraphQLString) }
},
resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
    ...
}

I would like to be able to pass either an 'id' or 'email' to the query, however, with this setup it requires both an id and email to be passed.

Is there a way to set up the query so only one argument is required, either id or email, but not both?


回答1:


There's no built-in way to do that in GraphQL. You need to make your arguments nullable (by removing the GraphQLNonNull wrapper type from both of them) and then, inside your resolver, you can just do a check like:

resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
  if (!id && !email) return Promise.reject(new Error('Must pass in either an id or email'))
  if (id && email) return Promise.reject(new Error('Must pass in either an id or email, but not both.'))
  // the rest of your resolver
}



回答2:


Define an interface credentials and have that implemented as id or email.



来源:https://stackoverflow.com/questions/46186518/how-do-i-set-up-graphql-query-so-one-or-another-argument-is-required-but-not-bo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!