|
| 1 | +include::attributes.adoc[] |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +[[codegen]] |
| 6 | += Code Generation |
| 7 | + |
| 8 | +You can use tools such as |
| 9 | +https://netflix.github.io/dgs/generating-code-from-schema/[DGS Code Generation] to generate |
| 10 | +Java types from the GraphQL schema. The following can be generated: |
| 11 | + |
| 12 | +1. Client types for requests (e.g. queries, mutations) input types, and response selection types. |
| 13 | +2. Data types corresponding to GraphQL schema types. |
| 14 | + |
| 15 | +Code generation may not be ideal for your own application's data types especially if you |
| 16 | +want to add logic to them. Code generation, however, is a good fit for client types since |
| 17 | +those define the request, and don't need to have other logic. As a client, you may also |
| 18 | +choose to generate the data types for the response. |
| 19 | + |
| 20 | +Client generated types can be used with Spring's `GraphQlClient`. Start by following the |
| 21 | +instructions for the DGS code generation plugin to generate client API types. Then, given |
| 22 | +a schema like this: |
| 23 | + |
| 24 | +[source,graphql,indent=0,subs="verbatim,quotes"] |
| 25 | +---- |
| 26 | + type Query { |
| 27 | + books: [Book] |
| 28 | + } |
| 29 | +
|
| 30 | + type Book { |
| 31 | + id: ID |
| 32 | + name: String |
| 33 | + } |
| 34 | +---- |
| 35 | + |
| 36 | +DGS Codegen generates `BooksGraphQLQuery` and `BooksProjectionRoot` that you can use with |
| 37 | +`GraphQlClient` over HTTP (or any supported transport) as follows: |
| 38 | + |
| 39 | +[source,java,indent=0,subs="verbatim,quotes"] |
| 40 | +---- |
| 41 | + HttpGraphQlClient client = |
| 42 | + HttpGraphQlClient.create(WebClient.create("http://localhost:8080/graphql")); |
| 43 | +
|
| 44 | + BooksGraphQLQuery query = new BooksGraphQLQuery(); |
| 45 | + String document = new GraphQLQueryRequest(query, new BooksProjectionRoot<>().id().name()).serialize(); |
| 46 | +
|
| 47 | + List<Book> books = client.document(document) |
| 48 | + .retrieve(query.getOperationName()) |
| 49 | + .toEntityList(Book.class) // possibly also generated or imported if available |
| 50 | + .block(); |
| 51 | +---- |
| 52 | + |
| 53 | +TIP: We intend to further simplify the above code in |
| 54 | +https://github.com/spring-projects/spring-graphql/issues/846[spring-graphql#846]. |
| 55 | + |
| 56 | +You can use Spring Initializer at https://start.spring.io to create a Spring project with |
| 57 | +the DGS Code Generation Gradle or Maven plugin. |
0 commit comments