Creating a GraphQL database service with Kotlin, Ktor and Postgres
I was playing around with creating a simple GraphQL project that could connect to a Postgres database and build a schema automagically from the database metadata. Technically this example should work out of the box with any JDBC available database but milage may vary. This is not yet production ready but if you are looking to get started with Ktor, or GraphQL maybe this article can help you out.
Everything starts with Gradle
Here is the all important build.gradle.kts. I kept the dependencies as minimal as possible using Ktor, graphql-java and Postgres libs. You could substitute whatever JDBC libraries to fit your needs but I tested the code specifically with Postgres version 12. If you checkout the github repository you will notice that I also added a fatjar task in order to dockerize the project and throw the container it into my Kubernetes environment.
Here we bootstrap the Ktor application module, install base functionality and register our routing handler for GraphiQL and GraphQL post handler. I also make a call to getSchema that will introspect the tables and columns configured in the database and programatically generate a GraphQL schema.
This file goes in your resources directory and by default should be named application.conf. I added the db stanza which Ktor ignores by default but when the application starts I can use this configuration to initialize my data base connection provider. Any tables created in my gql_db will automatically be added to my GraphQL schema for queries or mutations.
This is the most intense code for the project but what it accomplishes is inspecting a JDBC connected database to map the tables and columns into GraphQL types and queries programatically.
In GraphQL you need to provide an implementation of a data fetcher for queries and mutations. I am using JDBC queries but you could substitute JPQL with Hibernate for example.
This is not a full fledged application and it is missing quite a few core features including authentication and sql joins but maybe you can find a useful code sample to help you along the path of building your GraphQL or Ktor application. If you are looking for a feature rich GraphQL database solution you should check out Hasura or DGraph.
You can check out the code repository on github. It contains some extra features to dockerize the project and the GraphiQL implementation.