├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── LICENSE
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
└── main
├── java
└── com
│ └── creactiviti
│ └── spring
│ └── boot
│ └── starter
│ └── graphql
│ ├── Arguments.java
│ ├── Fields.java
│ ├── GraphQLAutoConfiguration.java
│ ├── GraphQLController.java
│ ├── MutationBuilder.java
│ ├── Ping.java
│ ├── QueryBuilder.java
│ ├── SpelDataFetcher.java
│ ├── SubscriptionBuilder.java
│ ├── TypeBuilder.java
│ └── Types.java
└── resources
└── META-INF
└── spring.factories
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 |
12 | ### IntelliJ IDEA ###
13 | .idea
14 | *.iws
15 | *.iml
16 | *.ipr
17 |
18 | ### NetBeans ###
19 | nbproject/private/
20 | build/
21 | nbbuild/
22 | dist/
23 | nbdist/
24 | .nb-gradle/
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runabol/spring-boot-starter-graphql/3432a8e573c34af0a5d3a351586e7f140a91dce8/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot Starter GraphQL
2 |
3 | The aim of this project is to get you easily started with GraphQL running in your Spring Boot based apps.
4 |
5 | This project is based on the fine work made by the folks behind the [graphql-java](https://github.com/graphql-java/graphql-java) library.
6 |
7 | **Note**: To support GraphQL's [subscriptions](http://graphql.org/blog/subscriptions-in-graphql-and-relay/) feature this module depends on Spring 5's WebFlux module and therefore Spring Boot 2.
8 |
9 | # GraphQL Primer
10 |
11 | In its most basic definition, GraphQL is a **query language** for your API.
12 |
13 | Say you have a database of movies and you decide that you want to expose it to app developers through an API.
14 |
15 | One way you could go about it is by using the traditional REST API approach:
16 |
17 | ```
18 | GET /movies?q=big
19 |
20 | [
21 |
22 | {
23 | "id":"1",
24 | "title":"Big",
25 | "synopsis":"After a wish turns 12-year-old Josh Baskin into a 30-year-old man...",
26 | "duration":"1h44m",
27 | "images":[{
28 | "type":"thumbnail",
29 | "url":"http://...",
30 | "resolution":"150x200"
31 | },
32 | {
33 | "type":"full",
34 | "url":"http://...",
35 | "resolution":"1920x1080"
36 | }],
37 | "genres":[...],
38 | "cast":[
39 | {
40 | "name":"Tom Hanks",
41 | "role":"..."
42 | }
43 | ]
44 | },
45 |
46 | {
47 | "id":"2",
48 | "title":"The Big Lebowski",
49 | "synopsis":"Jeff Bridges plays Jeff Lebowski who insists on being called "the Dude,"...",
50 | "duration":"1h57m",
51 | "images":[{
52 | "type":"thumbnail",
53 | "url":"http://...",
54 | "resolution":"150x200"
55 | },
56 | {
57 | "type":"full",
58 | "url":"http://...",
59 | "resolution":"1920x1080"
60 | }],
61 | "genres":[...],
62 | "cast":[
63 | {
64 | "name":"...",
65 | "role":"..."
66 | }
67 | ]
68 | }
69 |
70 | ...
71 |
72 | ]
73 | ```
74 |
75 | While this approach is totally workable it presents several challenges:
76 |
77 | 1. **Waste**. Let's say the app developers is building a screen that gives a movie listing with a thumbnail of the movie. Since the app developer does not need the movie synopsis, cast, genres etc. they are going to throw away a lot of data that had to be collected and tranferred over the wire. That's a lot of waste. One common way that people used to solve this problem is by introducing a `fields` query parameter to their API where you specify the fields you want to get back. This is an okay approach but comes with a significant amount of complexity to implement in the backend and does not scale very well to nested properties.
78 |
79 | 2. **Lack of standardization**. REST-based APIs are extremely custom from one to the next which means that there is no standard way to interrogate them or explore them. You are at the mercy of the API author to write proper documenations and keep these up to date in order to understand how the API works.
80 |
81 | 3. **Evolution**. In REST world, when you need to add new properties to your response you can either take the chance of adding them and hoping nothing breaks or you can add a `/v2/movies` endpoint and add your properties there. This could quickly get out of hand and adds an additional dimension to your API which you would do great without.
82 |
83 | 4. **Taxing the Backend**. When you create the first version of your API it's typically nice and fast. But as you introduce more database joins, more external calls required for your response and more calculations things start slowing down. This impacts not just the new features of your apps that need the new pieces of data but any festures that use the API.
84 |
85 | ## GraphQL to the rescue
86 |
87 | Alternatively, using GraphQL we expose a single endpoint (typically `/graphql`) which accepts a GraphQL query from the client and responds with the requested data. Here's an example:
88 |
89 | ```
90 | POST /graphql
91 |
92 | {
93 | getAllMovies {
94 | id // this is a field
95 | title,
96 | image(type:"thumbnail") { // fields can be nested
97 | url
98 | }
99 | }
100 | }
101 | ```
102 |
103 | ```
104 | [
105 |
106 | {
107 | "id":"1",
108 | "title":"Big",
109 | "image:{
110 | "url":"http://..."
111 | }
112 | },
113 |
114 | {
115 | "id":"2",
116 | "title":"The Big Lebowski",
117 | "image:{
118 | "url":"http://..."
119 | }
120 | }
121 | ]
122 | ```
123 |
124 | What just happened?
125 |
126 | 1. **Waste**. Since we only want to get the movie `id`, `title` and the thumbnail URL for each movie, that's exactly what we are getting back. The most of collecting and transferring the data is completely eliminated.
127 |
128 | 2. **Lack of standardization**. The GraphQL [spec](http://facebook.github.io/graphql/October2016/) provides a commong ground for agreement between API authors and client consumers. This opens the door for tools such as [GraphiQL](https://github.com/graphql/graphiql) and [Voyager](https://github.com/APIs-guru/graphql-voyager) to interrogate GraphQL-based APIs.
129 |
130 | 3. **Evolution**. Since GraphQL clients must *explicitly* request the pieces of information that they want to get back, there is no worry in adding new properties to the API and breaking older clients.
131 |
132 | 4. **Taxing the backend**. Since the client is only asking for exactly what it needs, the backend it free to only perform the necessary calculations and data retrieval operations necessary to fullfill the request.
133 |
134 | GraphQL has many more advantages and features but I hope that this gives you a good sense of what's possible with GraphQL.
135 |
136 | For more information check out the offical [GraphQL](http://graphql.org/) website.
137 |
138 | # Usage
139 |
140 | Add the `spring-boot-starter-graphql` dependency to your Spring Boot app:
141 |
142 | ```
143 |
144 | com.creactiviti
145 | spring-boot-starter-graphql
146 | 0.0.1-SNAPSHOT
147 |
148 |
149 |
150 |
151 | maven-snapshots
152 | http://oss.sonatype.org/content/repositories/snapshots
153 | default
154 |
155 | false
156 |
157 |
158 | true
159 |
160 |
161 |
162 | ```
163 |
164 | # Kicking the tires
165 |
166 | `spring-boot-starter-graphql` comes with a built-in `ping` query to test that everything is fine:
167 |
168 | ```
169 | $ curl -s -X POST -H "Content-Type:application/json" -d '{"query":"{ ping }"}' http://localhost:8080/graphql
170 |
171 | {
172 | "data": {
173 | "ping": "OK"
174 | },
175 | "errors": [],
176 | "extensions": null
177 | }
178 | ```
179 |
180 | # Your first GraphQL Query
181 |
182 | ```
183 | @Component
184 | public class HelloWorld implements QueryBuilder {
185 |
186 | @Override
187 | public void build (Builder aBuilder) {
188 | aBuilder.field(Fields.field("hello") // queries are just fields on the schema's built-in Query type.
189 | .type(Scalars.GraphQLString)
190 | .staticValue("Hi there!"));
191 | }
192 |
193 | }
194 | ```
195 |
196 | ```
197 | curl -s -X POST -H "Content-Type:application/json" -d '{"query":"{ hello }"}' http://localhost:8080/graphql
198 |
199 | {
200 | "data": {
201 | "hello": "Hi there!"
202 | },
203 | "errors": [],
204 | "extensions": null
205 | }
206 | ```
207 |
208 | # Your second GraphQL query
209 |
210 | OK, let's fetch some data now to make this more interesting:
211 |
212 | ```
213 | @Component
214 | public class GetAllMoviesQuery implements QueryBuilder {
215 |
216 | @Override
217 | public void build (Builder aBuilder) {
218 | aBuilder.field(Fields.field("getAllMovies")
219 | .type(Types.list(Movie.REF)) // query result type
220 | .argument(Arguments.stringArgument("q")) // query arguments
221 | .dataFetcher((env) -> {
222 |
223 | // in the real-world you would probably
224 | // fetch the data from a database but
225 | // i'm keeping it simple for the example.
226 | // The point is that the data can come from
227 | // anywhere: database, another service,
228 | // calculated on the fly, etc.
229 |
230 | Map movie = new HashMap<>();
231 |
232 | movie.put("title", "Big");
233 | movie.put("synopsis", "After a wish turns 12-year-old Josh Baskin into a 30-year-old man...");
234 | movie.put("duration", "1h44m");
235 |
236 | return Arrays.asList(movie);
237 | }));
238 | }
239 |
240 | }
241 | ```
242 |
243 | ```
244 | @Component
245 | public class Movie implements TypeBuilder {
246 |
247 | public static final String NAME = "Movie";
248 | public static final GraphQLTypeReference REF = Types.ref(NAME);
249 |
250 | @Override
251 | public GraphQLType build () {
252 | return Types.objectTypeBuilder()
253 | .name(NAME)
254 | .field(Fields.notNull(Fields.stringField("id")))
255 | .field(Fields.stringField("title"))
256 | .field(Fields.stringField("synopsis"))
257 | .field(Fields.stringField("duration"))
258 | .field(Fields.field("image")
259 | .argument(Arguments.stringArgument("type"))
260 | .type(Image.REF)
261 | .dataFetcher((env) -> {
262 |
263 | // fetch the right image.
264 |
265 | // will NOT be executed if the user
266 | // did not ask for the image field!
267 |
268 | })
269 | )
270 | .build();
271 | }
272 |
273 | }
274 | ```
275 |
276 | ```
277 | $ curl -s -X POST -H "Content-Type:application/json" -d '{"query":"{ getAllMovies { title synopsis } }"}' http://localhost:8080/graphql
278 |
279 | {
280 | "data": {
281 | "getAllMovies": [
282 | {
283 | "title": "Big",
284 | "synopsis": "After a wish turns 12-year-old Josh Baskin into a 30-year-old man..."
285 | }
286 | ]
287 | },
288 | "errors": [],
289 | "extensions": null
290 | }
291 | ```
292 |
293 | # Mutations
294 |
295 | So far we looked at reading data from the API. Mutations are GraphQL's approach to writing data.
296 |
297 | ```
298 | @Component
299 | public class AddMovie implements MutationBuilder {
300 |
301 | @Override
302 | public void build (Builder aBuilder) {
303 | aBuilder.field(Fields.field("addMovie")
304 | .argument(Arguments.notNull(Arguments.stringArgument("title")))
305 | .argument(Arguments.stringArgument("synopsis"))
306 | .argument(Arguments.stringArgument("duration"))
307 | .type(Movie.REF)
308 | .dataFetcher((env) -> {
309 | Map record = new HashMap<>();
310 |
311 | record.put("id", UUID.randomUUID().toString().replace("-",""));
312 | record.put("title", env.getArgument("title"));
313 | record.put("synopsis", env.getArgument("synopsis"));
314 | record.put("duration", env.getArgument("duration"));
315 |
316 | // save the the database
317 |
318 | return record;
319 | }));
320 | }
321 |
322 | }
323 | ```
324 |
325 | ```
326 | $ curl -s -X POST -H "Content-Type:application/json" -d '{"query":"mutation { addMovie (title:\"Big Fish\") { id title } }"}' http://localhost:8080/graphql
327 |
328 | {
329 | "data": {
330 | "addMovie": {
331 | "id": "8294094ebb034c7f82ef1170b95f69b0",
332 | "title": "Big Fish"
333 | }
334 | },
335 | "errors": [],
336 | "extensions": null
337 | }
338 | ```
339 |
340 |
341 |
342 | # Subscriptions
343 |
344 | Both queries and mutations make use of the traditional request/response model: the client makes a request with the specifics of what it wants to get back and the server responds appropriately.
345 |
346 | Subscriptions on the other hand, are publish/subsribe based mechanism: the server published some sort of notifications that clients can subscribe to.
347 |
348 | For example we can let clients know whenever a movie was added:
349 |
350 | ```
351 | @Component
352 | public class MovieAddedSubscription implements SubscriptionBuilder {
353 |
354 | private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
355 |
356 | @Override
357 | public void build (Builder aBuilder) {
358 | aBuilder.field(Fields.field("movieAdded")
359 | .type(Movie.REF)
360 | .dataFetcher((env)->Flux.create ((emitter) -> {
361 |
362 | // use a scheduled executor to simulate an
363 | // event happening on another thread event
364 | // second.
365 |
366 | executor.scheduleAtFixedRate(() -> onMovieAdded(emitter), 1, 1, TimeUnit.SECONDS);
367 |
368 | })));
369 | }
370 |
371 | private void onMovieAdded (FluxSink