Node Fastify with PostgreSQL.
In this article, I will explain about Fastify with PostgresSQL.
Install and understand about PostgreSQL
Before we start Fastify with PostgreSQL project we should have installed PostgreSQL in the machine.
$ sudo apt update
$ sudo apt install postgresql postgresql-contrib
If you want to learn more about PostgreSQL read this doc.
According to Postgres, your default account is ‘postgres
’. It is not good practice to create DB in this account so we need to create another account.
$ sudo -u postgres createuser --interactive
The above comment is to create a new user. I created a new user ‘demo’.
Then should create DB.
$ sudo -u demo createdb demo
I created DB called ‘demo’ in the ‘demo’ account.
We also want to create Table.
CREATE TABLE users(id, name, email);
Let me move to further more.
Understand about Fastify
Read this doc for more understanding about this framework.
Start with example
Initial setup and installation.
$ mkdir heroku-postgres
$ cd heroku-postgres
Install the needed plugins.
$ npm install fastify pg
$ npm install --save-dev nodemon
Your package.json should be like below.
Setup our index.js file.
The above picture is the basic setup for one simple project.
$ npm start
Open your browser in this address http://localhost:3000
Integrate with PostgreSQL
Click this link for mere understanding about this plugin
Initial setup for pg.
The first step get all data from the ‘users’ table.
Get all data
Get particular data by id
The above code gets the user which id is matched.
Insert data
Using the above code we can create new users.
Edit/Update
Using the above code we can edit users if the user already existed.
Delete
Using the above code delete the user from the database.
The full code for queries
Connect with Fastify
In the index.js file set your method.
These are methods are node method ‘get, post, put, delete’.
The above code for setup our methods.
Full index.js
Postman for testing API
Click this link for getting postman.
Below images for postman API.
Reference link:
Git link: