DEV Community

Antoine CHEVALIER
Antoine CHEVALIER

Posted on

How to successfully start with Nest.js and Postgres

In this tutorial will see how to install, configure postgres with Nest.js typeorm.

Postgres

1. Let's install Postgres

Install postgres on the official website. I'll recommend installing it on the official website rather then using homebrew cause it could lead to some trouble later

2. Basic of Postgres

  • Start Postgres app and start server
    Image description

  • Open your terminal and add psql to your path.

export PATH="/Applications/Postgres.app/Contents/Versions/9.5/bin:$PATH"

Image description

Basic Command

To open psql terminal : psql postgres
Image description

  • List all Database with \l
    Image description``

  • Create a Database with CREATE DATABASE name;
    Image description

  • Connect to a Database with \c name
    Image description

  • Exit postgres with \q
    Image description

Nest

Setup Nest Project

npm i -g @nest/cli
nest new project-name

Create .env file for the config of our Database

Create a .env file containing the PORT, USERNAME, DATABASE NAME, URL ...

PORT=4242
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_DB=nest
POSTGRES_HOST=localhost

Configure App Module

Inside your app module add the .env config file :

import { ConfigModule } from '@nestjs/config';
ConfigModule.forRoot({ envFilePath: ['.env'] })

Configure and install TypeOrm

Install Typeorm postgres for Next :

npm install --save @nestjs/typeorm typeorm postgres

Then import our configuration inside the app.module :

import { TypeOrmModule } from '@nestjs/typeorm'
TypeOrmModule.forRoot({
type: 'postgres',
host: 'process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
database: process.env.POSTGRES_DB,
entities: [],
synchronize: true,
logging: true,
autoLoadEntities: true,
})

Little explanation
synchronize: true,
autoLoadEntities: true,

Allow schema to be automatically with Database.

Little explanation
logging: true

Log all the interaction with the Database

Create Entity

Create a user.entity.ts file inside an entities folder.

Image description
I won't go into detail about this code cause you can find good documentation on Typeorm website.

`import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
} from 'typeorm';

@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
username: string;

@Column()
email: string;

@Column()
password: string;

@Column({
nullable: true,
unique: true,
})
access_token: string;

@CreateDateColumn()
created_at: Date;
}`

Then inside your app.module add entities: [User]

Top comments (0)