Skip to content

Commit 779cc76

Browse files
committed
Add reference docs section on codegen
Closes gh-847
1 parent acdd2a1 commit 779cc76

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Diff for: spring-graphql-docs/modules/ROOT/nav.adoc

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* xref:observability.adoc[]
88
* xref:graalvm-native.adoc[]
99
* xref:client.adoc[]
10+
* xref:codegen.adoc[]
1011
* xref:graphiql.adoc[]
1112
* xref:testing.adoc[]
1213
* xref:boot-starter.adoc[]

Diff for: spring-graphql-docs/modules/ROOT/pages/codegen.adoc

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
[[codegen]]
2+
= Code Generation
3+
4+
You can use tools such as
5+
https://netflix.github.io/dgs/generating-code-from-schema/[DGS Code Generation] to generate
6+
Java types from the GraphQL schema. The following can be generated:
7+
8+
1. Client types for requests (e.g. queries, mutations) input types, and other types to
9+
express the response selection set.
10+
2. Data types.
11+
3. Server handling classes (e.g. controllers).
12+
13+
Code generation provides convenience initially, but is not ideal for your own application
14+
domain types over which you'll typically want control. For client types, however, code
15+
generation can be very useful since you typically don't need to manually change generated
16+
request types, input types, and selection set types. Response types could be imported,
17+
if you have access to them, or otherwise could also be generated.
18+
19+
Client generated types can be used with Spring's `GraphQlClient`. Start by following the
20+
instructions for the DGS code generation plugin to generate client API types. Then, given
21+
a schema like this:
22+
23+
[source,graphql,indent=0,subs="verbatim,quotes"]
24+
----
25+
type Query {
26+
books: [Book]
27+
}
28+
29+
type Book {
30+
id: ID
31+
name: String
32+
}
33+
----
34+
35+
DGS Codegen will generate a `BooksGraphQLQuery` and `BooksProjectionRoot` classes.
36+
You can then use those with Spring's `GraphQlClient` along with your own `Book` class
37+
for the response:
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)
50+
.block();
51+
----
52+
53+
NOTE: Spring Initializer at https://start.spring.io is scheduled to add support for the DGS
54+
Code Generation with Gradle and Maven. See
55+
https://github.com/spring-io/start.spring.io/pull/1348[start.spring.io#1348].

0 commit comments

Comments
 (0)