【问题标题】:How to define an empty Object Type in a GraphQL schema?如何在 GraphQL 模式中定义一个空的对象类型?
【发布时间】:2021-09-22 03:24:24
【问题描述】:

我想在一个模式中指定我的 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!
}

Query 对象类型在另一个文件 schema.graphql 中定义:

schema {
    query: Query
    mutation: Mutation
}

type Query {
    dummyField: Boolean
}

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

对于type Query,我包含了dummyField,因为我无法在不出错的情况下定义空对象类型(没有字段的对象类型)。以下几行:

type Query {}

type Query {
}

抛出如下错误:

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

我希望这些对象类型为空,以避免dummyField 污染我的代码,并明确表示打算在其他文件中扩展QueryMutation

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

【问题讨论】:

    标签: graphql


    【解决方案1】:

    经过一番挖掘,我发现了这个GitHub Issue Comment,语法如下:

    type Query
    
    extend type Query {
      a: Boolean;
    }
    

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

    GraphQL 规范here 表明ObjectTypeDefinitionFieldsDefinition 是可选的,尽管这不是很清楚。

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2020-07-02
      • 2021-01-09
      • 2020-09-29
      • 2022-01-03
      • 2022-08-15
      • 2020-01-02
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多