我如何设置 GraphQL 查询以便需要一个或另一个参数,但不能同时使用 [英] How do I set up GraphQL query so one or another argument is required, but not both

查看:17
本文介绍了我如何设置 GraphQL 查询以便需要一个或另一个参数,但不能同时使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始掌握 GraphQL,

I'm just getting to grips with GraphQL,

我设置了以下查询:

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

我希望能够将id"或email"传递给查询,但是,通过此设置,它需要传递 id 和电子邮件.

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.

有没有办法设置查询以便只需要一个参数,id 或 email,而不是两者?

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

推荐答案

在 GraphQL 中没有内置的方法来做到这一点.您需要使您的参数可以为空(通过从它们中删除 GraphQLNonNull 包装器类型),然后在您的解析器中,您可以执行如下检查:

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
}

这篇关于我如何设置 GraphQL 查询以便需要一个或另一个参数,但不能同时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆