GraphQL Full-Stack Demo

This demo project demonstrates a full-stack application using GraphQL with a React frontend and a Java backend. The backend is built using Spring Boot, which exposes a GraphQL API, while the frontend is developed using React to consume the API.

GraphQL Full-Stack Demo

Backend

The backend is built using Spring Boot, which provides a robust foundation for building web applications. It includes the necessary dependencies for GraphQL integration and data persistence.

The first step is defining the type schema for the GraphQL API. This schema defines the structure of the data and the available queries and mutations. The schema is defined in a .graphqls file, which is automatically picked up by Spring Boot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
type Query {
users: [User!]!
user(id: ID!): User
posts: [Post!]!
}

type Mutation {
createUser(name: String!, email: String!): User!
createPost(title: String!, content: String, authorId: ID!): Post!
}

type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}

type Post {
id: ID!
title: String!
content: String
authorId: ID!
author: User!
}

Then initializing the dataset by creating a DataInitializer class that seeds the database with initial data.

DataInitializer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Configuration
public class DataInitializer {

@Bean
CommandLineRunner seedData(
UserRepository userRepository,
PostRepository postRepository
) {
return args -> {
if (userRepository.count() > 0) {
return;
}

User alice = userRepository.save(
new User("Alice", "alice@example.com")
);

User bob = userRepository.save(
new User("Bob", "bob@example.com")
);

postRepository.save(
new Post(
"Learning GraphQL",
"My first GraphQL post.",
alice.getId()
)
);

postRepository.save(
new Post(
"GraphQL vs REST",
"GraphQL lets the client select fields.",
alice.getId()
)
);

postRepository.save(
new Post(
"PostgreSQL Basics",
"PostgreSQL stores the actual data.",
bob.getId()
)
);
};
}
}

The Second step is creating a UserGraphqlController class that defines the GraphQL queries and mutations for the User entity. This controller handles requests from the frontend and interacts with the database through the repositories.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Controller
public class UserGraphqlController {

private final UserRepository userRepository;
private final PostRepository postRepository;

public UserGraphqlController(
UserRepository userRepository,
PostRepository postRepository
) {
this.userRepository = userRepository;
this.postRepository = postRepository;
}

@QueryMapping
public List<User> users() {
return userRepository.findAll();
}

@QueryMapping
public User user(@Argument Long id) {
return userRepository.findById(id).orElse(null);
}

@MutationMapping
public User createUser(
@Argument String name,
@Argument String email
) {
return userRepository.save(new User(name, email));
}

// Resolver for User.posts.
// This method runs only when the client asks for the "posts" field.
@SchemaMapping(typeName = "User", field = "posts")
public List<Post> posts(User user) {
return postRepository.findByAuthorId(user.getId());
}
}

Frontend

The frontend is built using React, which provides a dynamic and responsive user interface. It uses Apollo Client to interact with the GraphQL API exposed by the backend. The frontend includes components for displaying users and their posts, as well as forms for creating new users and posts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import { useState } from "react";
import { gql } from "@apollo/client";
import { useMutation, useQuery } from "@apollo/client/react";

const GET_USERS = gql`
query GetUsers {
users {
id
name
email
posts {
id
title
content
}
}
}
`;

const CREATE_USER = gql`
mutation CreateUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`;

const CREATE_POST = gql`
mutation CreatePost(
$title: String!
$content: String
$authorId: ID!
) {
createPost(
title: $title
content: $content
authorId: $authorId
) {
id
title
content
author {
id
name
}
}
}
`;

export default function App() {
const { data, loading, error } = useQuery(GET_USERS);

const [createUser, createUserState] = useMutation(CREATE_USER, {
refetchQueries: [{ query: GET_USERS }],
awaitRefetchQueries: true
});

const [createPost, createPostState] = useMutation(CREATE_POST, {
refetchQueries: [{ query: GET_USERS }],
awaitRefetchQueries: true
});

const [userForm, setUserForm] = useState({
name: "",
email: ""
});

const [postForm, setPostForm] = useState({
title: "",
content: "",
authorId: ""
});

async function handleCreateUser(event) {
event.preventDefault();

await createUser({
variables: {
name: userForm.name,
email: userForm.email
}
});

setUserForm({
name: "",
email: ""
});
}

async function handleCreatePost(event) {
event.preventDefault();

await createPost({
variables: {
title: postForm.title,
content: postForm.content || null,
authorId: postForm.authorId
}
});

setPostForm({
title: "",
content: "",
authorId: postForm.authorId
});
}

if (loading) {
return <main className="page">Loading GraphQL data...</main>;
}

if (error) {
return (
<main className="page">
<h1>GraphQL Demo</h1>
<p className="error">{error.message}</p>
<p>Make sure PostgreSQL and the Spring Boot backend are running.</p>
</main>
);
}

const users = data?.users ?? [];

return (
<main className="page">
<header>
<p className="eyebrow">React + Apollo + Spring Boot + PostgreSQL</p>
<h1>GraphQL Full-Stack Demo</h1>
<p>
The browser sends GraphQL operations to Spring Boot.
Spring resolvers load and store the actual data in PostgreSQL.
</p>
</header>

<section className="grid">
<form className="panel" onSubmit={handleCreateUser}>
<h2>Create user</h2>

<label>
Name
<input
value={userForm.name}
onChange={(event) =>
setUserForm({
...userForm,
name: event.target.value
})
}
required
/>
</label>

<label>
Email
<input
type="email"
value={userForm.email}
onChange={(event) =>
setUserForm({
...userForm,
email: event.target.value
})
}
required
/>
</label>

<button disabled={createUserState.loading}>
{createUserState.loading ? "Creating..." : "Create user"}
</button>

{createUserState.error && (
<p className="error">{createUserState.error.message}</p>
)}
</form>

<form className="panel" onSubmit={handleCreatePost}>
<h2>Create post</h2>

<label>
Author
<select
value={postForm.authorId}
onChange={(event) =>
setPostForm({
...postForm,
authorId: event.target.value
})
}
required
>
<option value="">Choose an author</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.name}
</option>
))}
</select>
</label>

<label>
Title
<input
value={postForm.title}
onChange={(event) =>
setPostForm({
...postForm,
title: event.target.value
})
}
required
/>
</label>

<label>
Content
<textarea
rows="4"
value={postForm.content}
onChange={(event) =>
setPostForm({
...postForm,
content: event.target.value
})
}
/>
</label>

<button disabled={createPostState.loading}>
{createPostState.loading ? "Creating..." : "Create post"}
</button>

{createPostState.error && (
<p className="error">{createPostState.error.message}</p>
)}
</form>
</section>

<section>
<h2>Users and their posts</h2>

<div className="users">
{users.map((user) => (
<article className="user-card" key={user.id}>
<div>
<h3>{user.name}</h3>
<p className="muted">{user.email}</p>
<p className="muted">User ID: {user.id}</p>
</div>

<div>
<h4>Posts</h4>

{user.posts.length === 0 ? (
<p className="muted">No posts yet.</p>
) : (
<ul>
{user.posts.map((post) => (
<li key={post.id}>
<strong>{post.title}</strong>
{post.content && <p>{post.content}</p>}
</li>
))}
</ul>
)}
</div>
</article>
))}
</div>
</section>

<section className="panel flow">
<h2>What happens when this page loads?</h2>
<pre>{`React useQuery(GET_USERS)
|
v
Apollo Client
|
POST http://localhost:8081/graphql
|
v
@QueryMapping users()
|
v
UserRepository.findAll()
|
v
PostgreSQL

Because the query also asks for User.posts:

@SchemaMapping User.posts
|
v
PostRepository.findByAuthorId(...)
|
v
PostgreSQL
|
v
GraphQL JSON response
|
v
Apollo cache
|
v
React renders the result`}</pre>
</section>
</main>
);
}

References