简体   繁体   中英

How to define an empty Object Type in a GraphQL schema?

I want to specify my GraphQL API in a schema, but I also want to spread my schema out among multiple files. I want to be able to use extend type Query or extend type Mutation to add queries or mutations to the overall schema. For example, my user.graphql file is as follows:

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

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

extend type Query {
    user(userId: ID!): UserResult!
}

The Query Object Type is defined in a different file, schema.graphql :

schema {
    query: Query
    mutation: Mutation
}

type Query {
    dummyField: Boolean
}

These files are combined when my application launches to produce the full API schema.

For type Query I have included a dummyField because I can't define an empty Object Type (one without fields) without getting an error. The following lines:

type Query {}

and

type Query {
}

Throw errors like:

line 988, in expect_token f"Expected {get_token_kind_desc(kind)}, found {get_token_desc(token)}.", graphql.error.syntax_error.GraphQLSyntaxError: Syntax Error: Expected Name, found '}'.

I would prefer for these Object Types to be empty to avoid the dummyField polluting my code and to make it clear that the intention is for Query and Mutation to be extended in other files.

I am using Flask with ariadne (0.13.0), which relies on graphql-core (3.1.5). I could not find anything in the most recent GraphQL specification about empty Object Types. Is it possible to declare empty Object Types in the schema, without using a placeholder field? If so, what is the correct syntax?

After some digging I found this GitHub Issue Comment with the following syntax:

type Query

extend type Query {
  a: Boolean;
}

I applied this to the examples above and they worked. Therefore, to create an empty Object Type, omit the curly braces { ... } .

The GraphQL specification here indicates that the ObjectTypeDefinition 's FieldsDefinition is optional, although this is not abundantly clear.

GraphQL 2018 年 6 月版第 3.6 节 ObjectTypeDefinition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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