Setup FastGQL
This tutorial will take you through the process of building a GraphQL server with fastgql that can: automatically query, filter, order and pagination users, posts & categories from a postgres database.
You can find the finished code for this tutorial here.
If you are familiar with gqlgen, the setup is nearly identical, with a little work in your Schema you won’t need to define any resolvers!
Setup Project
Create a directory for your project, and initialise it as a Go Module:
Add github.com/roneli/fastgql to your project’s tools.go
Building the server
Create the project skeleton
This will create our suggested package layout. You can modify these paths in gqlgen.yml if you need to.
Define your schema
gqlgen is a schema-first library — before writing code, you describe your API using the GraphQL Schema Definition Language. By default this goes into a file called schema.graphql
but you can break it up into as many different files as you want.
The schema that was generated for us was:
{% code overflow=“wrap” %}
{% endcode %}
Implement the resolvers
fastgql generate
compares the schema file (schema.graphql
) with the models graph/model/*
and wherever it can it will bind directly to the model. It generates resolvers just like gqlgen, but also implements some resolvers to directly work with the database.
If we take a look in graph/schema.fastgql.go
you will see all the resolvers that fastgql autogenerated for example:
{% code overflow=“wrap” %}
{% endcode %}
We just need to start a postgres server and insert a schema, you can try the example’s compose file and execute the schema.sql:
Finally, we just need to define our postgres connection str that defined in server.go. We can override with PG_CONN_STR
env variable.
If we used the example’s docker compose we can use this DSN: PG_CONN_STR=postgresql://localhost/postgres?user=postgres&password=password
We now have a working server, to start it:
then open http://localhost:8080 in a browser. here are some queries to try:
Finishing touches
At the top of our server.go
, between package
and import
, add the following line:
This magic comment tells go generate
what command to run when we want to regenerate our code. To run go generate recursively over your entire project, use this command: