NestJS Database Communication Flow:
The 'pg'(PostgreSQL NodeJS library) library was used for communicating with the PostgreSQL database. The 'typeorm'(NodeJS library) library is a framework used for querying the database or manipulating the database using the specified database library(in our case 'pg' node library). The 'typeorm' will be used for all database configurations also. The '@nestjs/typeorm'(NestJS ORM library) is an overlay or wrapper for the 'typeorm'(NodeJS library). By using '@nestjs/typeorm' it gives the advantage of Typescript compatibility and additional feature over 'typeorm'(NodeJS library). So while implementing NestJS application in max scenarios we will only use the '@nestjs/typeorm' library which will internally communicate with 'typeorm'(NodeJS library).
PostgreSQL Database Using ElephantSQL Cloud Service:
Create A Sample NestJS App:
Command To Install Nest CLI:
npm i -g @nestjs/cli
NestJS CLI Command To Create APP:
nest new your_project_name
By default NestJS application configured to run on portnumber '3000'. So execute the below command to start the application.
Commands To Start App:
npm run start
or
npm run start:dev ---> runs application in watch mode prefered for development time
or
npm run start:prod ---> production mode
Npm Packages:
Install NestJS Typeorm:
npm install --save @nestjs/typeorm
Install NodeJS Typeorm:
npm install --save typeorm
Install NodeJS PostgreSQL:
npm install --save pg
typeorm Decorators For Table Entities:
Create An Employee Table Entity:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class Employee { @PrimaryColumn()
id: number; @Column() name: string; @Column() salary: number; @Column() age: number; }
- (Line: 1) all required decorators are imported from the 'typeorm'(NodeJS library)
- (Line: 3) typescript class Employee decorated with '@Entity()' decorator to make it as table class.
- (Line: 5) 'id' property decorated with '@PrimaryColumn' decorator to make compatible with the primary column of the table.
- @column() decorator was used on all other properties of the typescript class to represent the table columns.
TypeOrmModule Of @nestjs/typeorm:
- forRoot() - this method takes configuration like database settings to set up communication between the NestJS application and the database. This method always registered in the parent or root module of the application like the 'app module'.
- forFeature() - this method is similar to the forRoot() method but it will be registered for child modules of the 'appmodule'.
- forRootAsync() - this async form forRoot() method.
Add PostgreSQL Configuration To AppModule:
import { TypeOrmModule } from '@nestjs/typeorm'; import { Employee } from './Employee/employee.entity'; // some code hidden for display purpose @Module({ imports: [ TypeOrmModule.forRoot({ type: 'postgres', host: 'lallah.db.elephantsql.com', port: 5432, username: '-----------', password: '-----------', database: '-----------', entities: [Employee], }) ] }) export class AppModule {}
- (Line: 7) 'type' defines the database will be used since we are using the PostgreSQL database so we can pass the constant value of 'postgres'.
- (Line: 8) 'host' database server hosted
- (Line: 9) the port number, '5432' is the default port number for the PostgreSQL database.
- (Line: 10&11&12) database username, password, name of the database
- (Line: 13) entities of the database need to register, it takes an array of entity types.
- Click here for identifying PostgreSQL configurations
Pre-defined Repository Of typeorm:
InjectRepository Decorator From @nestjs/typeorm:
Create EmployeeService:
import { Injectable } from '@nestjs/common'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; @Injectable() export class EmployeeService { constructor(@InjectRepository(Employee) private employeeRepo: Repository<Employee>) {} }
- (Line: 6) 'Injectable' decorator used on 'EmployeeService' to make it as an injectable service
- (Line: 8) 'Repository<Employee>' injected into the service class with the help of '@InjectRepository()' decorator.
Add Fetch All Employee Logic:
import { Employee } from './employee.entity'; // code hidden for display purpose @Injectable() export class EmployeeService { findAll(): Promise<Employee[]> { return this.employeeRepo.find(); } }
- The 'find()' method from the repository which will take optional filter parameters to query against the database. If no filter parameters passed it return all the data from the database.
- The 'find()' method returns a promise of an array of the entity type.
Create Employee Controller With Read Operation:
import { Controller, Get } from '@nestjs/common'; import {EmployeeService} from './employee.service'; import {Employee} from './employee.entity'; @Controller('employee') export class EmployeeController { constructor(private readonly employeeService: EmployeeService){} @Get('all') async getAll():Promise<Employee[]>{ return await this.employeeService.findAll(); } }
- '@Controller()' decorator that makes class as Nest controller that can receive the inbound request and produce the response.
- '@Get()' decorator is a route handler decorator. Routes Http Get request to the specified path.
- (Line: 7) injected 'EmployeeService'
- (Line: 9-12)Http method that executes read operation to fetch all the employee data.
Create An Employee Module:
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { EmployeeController } from './employee.controller'; import { Employee } from './employee.entity'; import { EmployeeService } from './employee.service'; @Module({ imports: [TypeOrmModule.forFeature([Employee])], providers: [EmployeeService], controllers: [EmployeeController], }) export class EmployeeModule {}
- 'TypeOrmModule.forFeature([Employee])' makes the 'Emplyee' entity schema available to 'Repository' from the 'typeorm'(NodeJS library) to query the database.
- 'EmployeeService' registered to providers array to load the service for the Employee module.
- 'EmployeeController' registered to controllers array to expose the routes.
Register Child Modules To AppModule:
import { EmployeeModule } from './Employee/employee.module'; // code hidden for display purpose @Module({ imports: [ EmployeeModule, ] }) export class AppModule {}Now start the application and access the newly created endpoint and output shows as below.
Create Operation:
create(newEmploye){ this.employeeRepo.insert(newEmploye) }'insert()' method provided by the 'Repository' imported from 'typeorm'(NodeJS library). This method inserts a given entity. Executes fast and efficient Insert queries. Doesn't check if the entity exists in the database, so the query will fail if a duplicate entity tries to insert.
import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common'; @Post('add') @HttpCode(201) createEmployee(@Body() newEmployee:any){ this.employeeService.create(newEmployee); }
- '@Post()' request handler decorator. Routes Http Post request to the specified path.
- '@HttpSatatusCode' request method decorator. Defines the Http response status code. Overrides default status code for the decorated request method. '201' status code stands for created successfully.
- '@Body()' route handler parameter decorator. Extract the entire body object from the request object and populate the decorated parameter with the value of the body.
Update Operation:
update(employeetoUpdate){ this.employeeRepo.update(employeetoUpdate.id,employeetoUpdate); }'update()' method from 'Repository' imported from 'typeorm'. This method is an overloaded method. It has the capability to do a partial update without effecting other column's data.
src/Employee/employee.controller.cs:
@Post('update') @HttpCode(200) updateEmployee(@Body() employeeToUpdate:any){ this.employeeService.update(employeeToUpdate); }
Delete Operation:
delete(id){ this.employeeRepo.delete(id); }'delete()' method of 'Repository' from 'typeorm'. Bypassing the primary key id is enough to remove the record from the database.
@Delete('delete/:id') @HttpCode(200) deleteEmployee(@Param('id') id){ this.employeeService.delete(id); }
- '@Delete()' route handler decorator. Routes Http Delete requests to the specified path.
- '@Param()' this decorator is to extract the data from the route.
Support Me!
Buy Me A Coffee
PayPal Me
This was well details article. It unveiled alot to help understand NESTJS
ReplyDelete