在 GraphQL 中是否可以构造一个查询以期望一个整数或一个整数数组?

Is it possible in GraphQL to structure a Query to expect an Integer, or an array of Integers?

我觉得它必须是强类型的,无论是哪种方式,我很好奇我是否可以用同一个查询完成这两种操作,我想要这样的事情:

{
  accounts(accountId: [1,2,3]) {
    ...
  }
}

并且还能够进行相同的调用,将其视为普通 int:

{
  accounts(accountId: 1) {
    ...
  }
}

List 是一种包装类型包装 另一种类型,但它本身是一种独特的类型。所以 Int[Int] 是两种不同的类型。字段或参数必须只有一种类型,因此它只能具有类型 Int 类型 [Int] -- 不能同时具有。

但是,您可以利用 GraphQL 如何强制 List 输入值。来自规范:

If the value passed as an input to a list type is not a list and not the null value, then the result of input coercion is a list of size one, where the single item value is the result of input coercion for the list’s item type on the provided value (note this may apply recursively for nested lists).

换句话说,如果accountId的类型是[Int](或[Int!][Int!]!),客户端仍然可以传入一个整数作为一个值而不是一个数组。在这种情况下,该值将被强制到具有单个值(传入的值)的数组中。

扩展 Daniel Reardon 的回答:不幸的是,无法使用不同的参数查询同一字段。针对这种情况的推荐技术是使用别名:

https://graphql.org/learn/queries/#aliases

但是,您可以根据传递给它的数组设计 API 到 return 不同的结果。因此,例如,如果数组中只有一项,则可以 return 只有一条记录,如果有很多,则可以 return 一条记录,如果数组为空,则可以是所有记录。

下面是一些可能看起来像的假设代码:

public IEnumerable<Accounts> GetAccounts(int[] accountIds)
{
    // if no items in array
    if (accountIds.Length == 0)
    {
        // return all accounts
        return Accounts.ToList();
    }

    // return only accounts that are in accountIds array
    // if only one item is in array, then an IEnumerable with only one item will be returned
    return Accounts
        .Where(b => accountIds.Contains(b.AccountId))
        .ToList();
}
如果传递的数组只有一个 ID,

Hot Chocolate's GetCharacters(int[] ids) method in the Star Wars API example 也将 return 只有一个字符,如果数组中有多个项目,则

也将是多个字符:

public IEnumerable<ICharacter> GetCharacters(int[] ids)
        {
            foreach (int id in ids)
            {
                if (_characters.TryGetValue(id, out ICharacter? c))
                {
                    yield return c;
                }
            }
        }