Go GraphQL API

A step-by-step guide to building a GraphQL API using Go and Ent. We will use Ent, a code-generation based ORM for Go, to interact with a PostgreSQL database. Ent also supports MySQL (and it’s variants) and a couple of others as the underlying database.

This is going to broken down into several sections where we will work on adding and integrating each piece into our application.

Project Setup

#golang  #graphql  #ent 

This first section is all about setting up the project. We will initialize our Go project and set up Cobra for handling the CLI parts of our application. Once we have this scaffolding in place we can move on to the larger parts of this.

Setting Up gqlgen

Now that we have an application scaffolded with Cobra we can set up gqlgen. This library is great because it will allow us to create our GraphQL schema files and generate the scaffolding for the parts of the app that need code to resolve them. It’s super developer friendly so don’t worry if it doesn’t make sense yet.

First ent Schema

#golang  #ent 

For our project, we are going to use ent as our backend datastore. When using ent we get the benefit of a code-generated client with strongly typed models for the database. It also supports a few different databases out of the box (SQLite, PostgreSQL, and MySQL), making it very easy to integrate into an existing workflow.

Database Seeding

#golang  #ent 

With our app in a healthy place, we can add database seeding. This is going to be quick because all we’re going to have to do is write a handful of ent create methods. We can make this more advanced with environment specific config and/or external files that we can embed using embed.FS.

Add Remaining Tests

With our resolver tests in place, we can turn our attention to testing the remainder of the application. Here we’re going to test the pkg/config, pkg/env, pkg/errors, pkg/sig, and finally the cmd. We won’t be testing main.go right now as testing main.go will be more of an end-to-end test. We can always create tests for it, but with the current simplicity of our main.go I’m not too worried about testing it using this method.