如何在 GraphQL 模式中定义空对象类型?

Joe*_*sey 10 graphql

我想在模式中指定我的 GraphQL API,但我也想将我的模式分布在多个文件中。我希望能够使用extend type Queryextend type Mutation向整个架构添加查询或突变。比如我的user.graphql文件如下:

type User {
    id: ID!
    name: String!
    email: String!
}

type UserResult {
    success: Boolean!
    errors: [String]
    user: User
}

extend type Query {
    user(userId: ID!): UserResult!
}
Run Code Online (Sandbox Code Playgroud)

对象Query类型在不同的文件中定义schema.graphql

schema {
    query: Query
    mutation: Mutation
}

type Query {
    dummyField: Boolean
}
Run Code Online (Sandbox Code Playgroud)

当我的应用程序启动时,这些文件将被合并以生成完整的 API 架构。

因为type Query我已经包含了 a ,dummyField因为我无法定义一个空的对象类型(没有字段的对象类型)而不出现错误。以下几行:

type Query {}
Run Code Online (Sandbox Code Playgroud)

type Query {
}
Run Code Online (Sandbox Code Playgroud)

抛出如下错误:

第988行,在expect_token f“预期{get_token_kind_desc(kind)},找到{get_token_desc(token)}。”,graphql.error.syntax_error.GraphQLSyntaxError:语法错误:预期名称,找到'}'。

我希望这些对象类型为空,以避免dummyField污染我的代码,并明确其目的是为了QueryMutation其他文件中扩展。

我将 Flask 与 ariadne (0.13.0) 一起使用,它依赖于 graphql-core (3.1.5)。我在最新的GraphQL 规范中找不到有关空对象类型的任何内容。是否可以在架构中声明空对象类型,而不使用占位符字段?如果是这样,正确的语法是什么?

Joe*_*sey 16

经过一番挖掘,我发现了这个GitHub 问题评论,其语法如下:

type Query

extend type Query {
  a: Boolean;
}
Run Code Online (Sandbox Code Playgroud)

我将其应用到上面的示例中并且它们起作用了。因此,要创建空对象类型,请省略大括号{ ... }

此处的GraphQL 规范表明是ObjectTypeDefinition可选FieldsDefinition的,尽管这一点还不是很清楚。

GraphQL 2018 年 6 月版第 3.6 节 ObjectTypeDefinition

  • 只是为了向未来的读者澄清,围绕这一点的规范似乎有点混乱,因为还有其他类型验证部分要求类型定义至少一个字段(https://spec.graphql.org/October2021/ #sel-FAHZhCFDBAACDA4qe)。此外,其他库(例如“sangria”和“graphql-java”)不支持空类型,如本示例所示。 (6认同)