Node Fastify with PostgreSQL.

Edison Devadoss
4 min readJul 12, 2019

In this article, I will explain about Fastify with PostgresSQL.

Google image

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.

https://carbon.now.sh

The first step get all data from the ‘users’ table.

Get all data

https://carbon.now.sh

Get particular data by id

https://carbon.now.sh

The above code gets the user which id is matched.

Insert data

https://carbon.now.sh

Using the above code we can create new users.

Edit/Update

https://carbon.now.sh

Using the above code we can edit users if the user already existed.

Delete

https://carbon.now.sh

Using the above code delete the user from the database.

The full code for queries

https://carbon.now.sh

Connect with Fastify

In the index.js file set your method.

These are methods are node method ‘get, post, put, delete’.

https://carbon.now.sh

The above code for setup our methods.

Full index.js

https://carbon.now.sh

Postman for testing API

Click this link for getting postman.

Below images for postman API.

ScrScreenshotank you for reading! Have a great Day!

--

--

Edison Devadoss

Software developer / JavaScript / React / React Native / Firebase / Node.js / C Programming / Book Reader