Spring Boot + Kotlin + GraphQL + MongoDB — Part 2: Mutations
Hack the stack.
Most discussions of GraphQL focus on data fetching, but any complete data platform needs a way to modify server-side data as well.
In REST, any request might end up causing some side-effects on the server, but by convention it’s suggested that one doesn’t use GET
requests to modify data. GraphQL is similar - technically any query could be implemented to cause a data write. However, it's useful to establish a convention that any operations that cause writes should be sent explicitly via a mutation.
- This post is a sequel to Spring Boot + Kotlin + GraphQL + MongoDB — Part 1.
- Demo project repository is available at GitHub.
Creating your first GraphQL mutation
In the previous post, I tried to explain how one can fetch Person
object from the MongoDB using GraphQL queries. In this post we are going to insert the Person
object into a database with the GraphQL mutations. Let’s go!
Update PersonDao
createPerson(name:)
method is appended to PersonDao
class which passes name
argument to the save(S)
method from PersonRepository
. As PersonRepository
implements CrudRepository
, so we got save(S)
method for free.
GraphQL input
Read about GraphQL input types.
Create person_input.graphqls
file inside resources/graphql/input
directory with following content:
input PersonInput {
name: String!
}
and the associated data class named PersonInput
inside graphql/input
package:
GraphQL mutation
Create mutation.graphqls
inside resources/graphql
directory with following content:
type Mutation {
# Creates person
personCreate(input: PersonInput!): Person!
}
Same method must exist in GraphQLMutationResolver
subclass, which is a Spring BootComponent
. A good place to put it is in the graphql
package:
PersonDao
is our connection to a data layer. Passing a name should create a Person
record in the database.
We’re done coding!
Executing mutation
Run mvn spring-boot:run
and execute some mutations in the GraphiQL interface!
mutation {
personCreate(name: "Joey Tribbiani") {
id
name
}
}
should return something like:
{
"data": {
"personCreate": {
"name": "Joey Tribbiani",
"id": "b6ff8f21-923f-43a4-b84a-9e81705c8159"
}
}
}
Congratulations, you have successfully connected GraphQL mutations to the MongoDB!