33
Secret to configuring the best Postgres-Nest project- Part 1

Notations
This project is divided into 4 parts
This project is divided into 4 parts
My Computer setup
Prerequisites
Installation
PART-1 ( Docker )
PART-1 ( Docker )
docker run --rm --name pg-docker -e POSTGRES_PASSWORD=poc-estm -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data postgres
--rm
is used to remove the constaine if it exists--name
is used to specify the name of the container-e
environment variables-d
in detached mode-p
port number to run on-v
volume to store the data internal to the container onpostgres
the image to pullThe below command will interactively log in to the TTY terminal of the container
docker exec -it pg-docker bash
once inside the psql prompt login to the DB and create a DB of ur choice (will be used in the code )
psql -h localhost -U postgres -d postgres
docker docs referances
PART-2 ( Nest Installation )
npm i -g @nestjs/cli
nest new <project-name>
Project Setup
Install the required Dependencies
run the following command to install the dependicies for typeorm and postgres
now run the following command in the new project folder created
this command will generate
Install the required Dependencies
run the following command to install the dependicies for typeorm and postgres
npm install --save @nestjs/typeorm typeorm mysql2
now run the following command in the new project folder created
nest generate module db
this command will generate
db
db.module.ts
in the above db
folder
we will need 2 other files basically interfaces and classes
db.interfaces.ts

db.errors.ts

db.module.ts
file

I am using
If you look at lines
convict
to set up the environment variables convictIf you look at lines
26
to 36
getConnectionOptions()
this function is responsible for creating the JSON that will act as the connector in Nesttype
is the type of the database that you want to connect to it can be (PostgreSQL, Oracle, Microsoft SQL Server, SQLite, and even NoSQL databases like MongoDB) host
the the dbhost
post
is the port you want to use to connect to the DB in our case it is 5432`database
databaseNamekeepConnectionAlive
is necessary to keep a connection open with the DB23
to 29
with url:<db-url>
app.module.ts

update your
app.module.ts
to look like aboveThe
forRoot()
is important here it is responsible for returning a DynamicModule which will create the connection for us with the Postgres DBPlease ignore lines 3 and 4 I will come to it in the next part of the article :)
Now we are ready to test ;)
run the following command in the terminal-
run the following command in the terminal-
npm run start:dev
If all goes well you will get no errors in case of any please revisit the steps to check what is different.
See you in the next part 😀
33