如何让 GraphQL 枚举解析字符串

How to have GraphQL enum resolve Strings

之前,我只是将我的 input KeyInput 键入 mode: String!,我希望将类型从 String 更改为!到自定义枚举。

我试过以下模式:

enum Mode= {
    test
    live
}

input KeyInput = {
    mode: Mode!
}

type Key {
    name,
    mode
}

type Query {
    Keys(input: KeyInput): [Key]
}

我的查询如下所示:

query{
     Keys(input: {mode: "test"}){
        name
     }
}

但是,我收到以下错误:

      "message": "Expected type Mode!, found \"test\"; Did you mean the enum value test?"

是否可以让枚举值解析字符串值?如果我从输入中删除引号,它将起作用。但是,我需要能够继续将模式解析为字符串。

来自spec

GraphQL has a constant literal to represent enum input values. GraphQL string literals must not be accepted as an enum input and instead raise a query error.

Query variable transport serializations which have a different representation for non‐string symbolic values (for example, EDN) should only allow such values as enum input values. Otherwise, for most transport serializations that do not, strings may be interpreted as the enum input value with the same name.

换句话说,当使用枚举作为输入时,如果您将其用作文字值,如下所示:

Keys(input: { mode: test }) {
  name
}

枚举值(在本例中为test)不能用引号引起来,这与必须用双引号括起来的字符串文字不同。

另一方面,如果您使用变量来替换枚举值,您会将变量的值设置为字符串,就像您对常规字符串值所做的那样:

Keys(input: { mode: $mode }) {
  name
}

// in your component...
variables: {
  mode: 'test'
}

因为 JSON 不包含枚举值的概念,所以每当我们处理 JSON 上下文时(例如,声明变量时,或返回 data for我们的请求),枚举值被简单地序列化为字符串值。

除此之外,如果您使用 Apollo 作为客户端,是否必须包含引号应该无关紧要——如果您需要替换 mode 输入字段的值,您应该使用变量来执行此操作,在这种情况下(如上所示),您将无论如何传递一个字符串值。