This repo contains:
- GraphQL (query - mutation)
- Spring Data Jpa
- Pagination
- GraphQL test
This repo show how to use graphQL with spring for represent data, also show how to test it.
Instruction for use GraphQL
- define graphql as directory on resources and create schema file into this directory
- write type of object which represent in Rest-APIs base on your models.
- use
type
keyword for define objects - use
ID
as type for id - use
!
to show this field have value and don't need check for null - use
[]
to show this field has more than one data - use
input
to define object that want use it in many request in mutation
- use
- define controller method and mapped query to the method
- use SchemaMapping ->
@SchemaMapping(typeName = "Query", value = "allBooks")
- use QueryMapping ->
@QueryMapping
and set name of method as same as query that define in schema
- use SchemaMapping ->
- sample query in UI
query { findOne(id:2) { id title pages rating{ star } author{ firstName lastName } } }
- sample mutation in UI
mutation{ update(coffeeForUpdate: { id: 4 name:"Hot Nescafe" size:TALL }) { name id size } }
- Sample Mutation with array
mutation BatchCreate { batchCreate(coffees: [ {name: "coffee One", size: SHORT}, {name: "coffee two", size: TALL}, {name: "coffee three", size: SHORT} ]){ id, name, size } }
if you want to extend scalar of graphQL, you must do this steps:
- add
graphql-java-extended-scalars
in pom file - use
scalar
keyword in schema.graphqls file in order define new scalar -> scalar BigDecimal - create config class to define
RuntimeWiringConfigurer
bean, in order to wire scalar BigDecimal - Another library that is useful for date is Tailrocks graphql java datetime
- define your own Exception which it extends from RuntimeException like
PersonQLException
- define a handler that it extends DataFetcherExceptionResolverAdapter and override
resolveToSingleError
method likePersonQLExceptionHandler
- also you can use your handler class for handle constraint validation
customer as an extended scalar sample written by using those steps.
Note:
-
Three Top level root Operation
Query -> define query
Mutation -> change data, creating, updating, deleting
Subscription -> read data and keep connection open for when changes -
In order to use graphical UI , first enable
spring.graphql.graphiql.enabled
in application properties,
and then write this URL in browser: http://localhost:8080/graphiql?path=/graphql
Special Thanks from Dan Vega for the tutorial about GraphQL