简体   繁体   English

GraphQL:查询中至少需要一个参数

[英]GraphQL: Require at least one argument in a query

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. 我想接受idemail作为参数,但至少需要一个。 Is there a way to set this up in the schema, without having to write extra code inside the resolve function? 有没有办法在模式中设置它,而不必在resolve函数中编写额外的代码?

Or would it be more advisable to create separate queries for each argument? 或者更为明确的是为每个参数创建单独的查询? For example: getUserById , getUserByEmail , getUserBySessionToken , etc? 例如: getUserByIdgetUserByEmailgetUserBySessionToken等?

I think the easiest way using resolve function. 我认为使用resolve函数最简单的方法。 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: 架构在graphql中可能如下所示:

type query {
  getUser(
    lookup: String!
    lookupType: UserLookupType!
  ): User
}

enum UserLookupType {
  ID
  EMAIL
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM