https://github.com/jusexton/spring-graphql-example
GraphQL example project using Kotlin and Spring Boot.
https://github.com/jusexton/spring-graphql-example
example-project graphql kotlin spring-boot
Last synced: about 2 months ago
JSON representation
GraphQL example project using Kotlin and Spring Boot.
- Host: GitHub
- URL: https://github.com/jusexton/spring-graphql-example
- Owner: jusexton
- Created: 2019-07-30T03:44:37.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2019-08-12T03:43:26.000Z (almost 7 years ago)
- Last Synced: 2025-07-31T22:58:02.058Z (11 months ago)
- Topics: example-project, graphql, kotlin, spring-boot
- Language: Kotlin
- Homepage:
- Size: 597 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Spring GraphQL Example
Small CRUD application demonstrating how to build a GraphQL API with Kotlin, MongoDB and Spring Boot.
You will need a mongo instance to connect too for this application to work.
## GraphQL Dependencies
```
implementation 'com.graphql-java:graphiql-spring-boot-starter:5.0.2'
implementation 'com.graphql-java:graphql-spring-boot-starter:5.0.2'
implementation 'com.graphql-java:graphql-java-tools:5.2.4'
```
## GraphiQL
### Adding New Users

```
type Mutation {
# Used to create a new user in the system
createUser(input: UserInput!): User!
}
```
```kotlin
fun createUser(userInput: UserInput) = userRepository.save(User(userInput.username, userInput.address))
```
### Querying Users

```
extend type Query {
# Retrieves a user by their id
userById(id: String!): User
# Used to retrieve all users in the system.
allUsers(filter: UserFilter): [User]!
}
```
```kotlin
fun userById(id: String) = userService.repository.findById(id).orElseThrow { UserNotFoundException(id) }
fun allUsers(filter: UserFilter?) = userService.findAll(filter)
```
### Error Messages

```kotlin
@Component
class ErrorHandler : GraphQLErrorHandler {
override fun processErrors(errors: MutableList?): MutableList =
errors?.map { getNested(it) }?.toMutableList() ?: mutableListOf()
private fun getNested(error: GraphQLError): GraphQLError =
if (error is ExceptionWhileDataFetching && error.exception is GraphQLError) error.exception as GraphQLError else error
}
```