Code Generation

你可以使用像 DGS Codegen这样的工具从 GraphQL 架构生成 Java 类型。可以生成以下内容:

You can use tools such as DGS Codegen to generate Java types from the GraphQL schema. The following can be generated:

  1. 请求的客户端类型(例如查询、变异)输入类型和响应选择类型。

  2. Client types for requests (e.g. query, mutation) input types, and response selection types.

  3. 与 GraphQL 模式类型相对应的数据类型。

  4. Data types corresponding to GraphQL schema types.

代码生成可能不适合你自己的应用程序的数据类型,尤其是如果你想向它们添加逻辑时。然而,代码生成非常适合客户端类型,因为这些类型定义请求,不需要有其他逻辑。作为一个客户端,你也可以选择为响应生成数据类型。

Code generation may not be ideal for your own application’s data types especially if you want to add logic to them. Code generation, however, is a good fit for client types since those define the request, and don’t need to have other logic. As a client, you may also choose to generate the data types for the response.

客户端生成的类型可以与 Spring 的 DgsGraphQlClient 一起使用。首先,按照 DGS 代码生成插件的说明进行操作,生成客户端 API 类型。然后,给定这样的架构:

Client generated types can be used with Spring’s DgsGraphQlClient. Start by following the instructions for the DGS code generation plugin to generate client API types. Then, given a schema like this:

具有 [role="bare"][role="bare"]https://start.spring.io 的 Spring Initializer 可以使用 DGS Codegen Gradle 或 Maven 插件创建一个 Spring 项目。

Spring Initializer at [role="bare"]https://start.spring.io can create a Spring project with the DGS Codegen Gradle or Maven plugin.