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.
Install 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 (
#Creating Database Connection
You'll need a running PostgreSQL instance before initializing the connection.
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 Provider
The 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
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
- And finally, create a data provider creator by using the
The rest of the code uses
buildGraphbackAPI to create Graphback CRUD API based on the defined
Visit Data Models pages to learn more about how to design your business models.