Using PostgreSQL with Graphback
PostgreSQL is a powerful, open source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance. Graphback Knex Provider package provides instant integration to your PostgreSQL database, giving you a full implementation of the CRUD API.
Additionally you can use GraphQL Migrations to perform database migrations using the models defined in the GraphQL schema created by Graphback.
The provider is built on top of Knex.js, a flexible SQL query builder.
#
InstallationInstall with npm:
Install with yarn:
Running either of the two commands will install the Graphback Knex Provider
(@graphback/runtime-knex
) and the Knex.js library (knex
).
#
Creating Database ConnectionYou'll need a running PostgreSQL instance before initializing the connection.
info
If you do not have a running instance, you can use Docker to quickly spin up a PostgreSQL container by following the instructions given in PostgreSQL Docker Image.
The above code initiates a connection to a local running PostgreSQL database, using the postgresql:password
credentials. We also create a database connection pool to a minimum of 5
and maximum of 30
. You can modify the configurations depending on your setup.
Visit Knex Connection Options to learn more about configuring your database connection and the different connection options.
#
Using Knex ProviderThe provider exposes a createKnexDbProvider
method, which can be used to create data providers for each of your data models.
The code below shows how you can create such a data provider creator and how it can be passed to buildGraphbackAPI
.
The highlighted code does the following:
- Define connection configuration to the database.
- Create a connection to PostgreSQL database using Knex.
- Define the user model.
- Perform the migrations using GraphQL Migrations to create the
user
table. - And finally, create a data provider creator by using the
createKnexDbProvider
API.
The rest of the code uses buildGraphbackAPI
to create Graphback CRUD API based on the defined userModel
model.
Visit Data Models pages to learn more about how to design your business models.