Skip to main content

NestJS API CRUD Operation Using PostgreSQL Relational Database

NestJS API is a server-side framework that runs on NodeJS frameworks like Express. NestJS application has the ability to talk with both SQL and Non-SQL databases.

Here we will develop a sample NestJS API application that communicates with the PostgreSQL relational database.

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:

So for our application, we need to set up a PostgreSQL relational database. Here I'm going to set up a free cloud service PostgreSQL database provided by ElephantSQL for our demo purpose. It is a very easy setup, to do it takes 3-5minutes to setup, click here for steps to configure the ElephantSQL cloud service.

Create A Sample NestJS App:

Let's begin our sample by creating a NestJS application. Here we use NestJS CLI(command line interface) to create 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
npm run start:dev ---> runs application in watch mode prefered for development time
npm run start:prod ---> production mode 

Npm Packages:

Install the following npm packages that are needed to accomplish our sample NestJS application.
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:

To make our typescript entity or model as table related entity, then we need to use decorators that are provided by the 'typeorm'(node js library).

@Entity() - This decorator is used to mark classes that will be an entity(table or document depends on database type). A database scheme will be created for all classes decorate with it, and the repository can be retrieved and used for it.

@PrimaryColumn() - This decorator is used to mark the property of an entity as a primary column of the table. It has the capability of the incremental integer value to save.

@Column() - This decorator is used to mark the property of class as the column of the table.

Create An Employee Table Entity:

In this sample, we are going to develop CRUD operations on the Employee table in the PostgreSQL relational database.

As a first step lets create a typescript Employee class that represents the database table.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

export class Employee {
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:

TypeOrmModule of @nestjs/typerorm(NestJs library) will be used to configure database settings, register table entities, register injectable repositories of entity types, etc. TypeOrmModule implements static overloaded methods like:
  • 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:

To establish communication with the PostgreSQL database need to add configuration in TypeOrmModule at app.module.ts file to register globally.
import { TypeOrmModule } from '@nestjs/typeorm';
import { Employee } from './Employee/employee.entity';
// some code hidden for display purpose
  imports: [
      type: 'postgres',
      host: '',
      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:

The 'typeorm'(NodeJS library) provides Pre-defined 'Repository<TEntity>'. This pre-defined 'Repository' is supposed to work with our entity objects. It responsibilities are like 'find entities', 'insert', 'update', 'delete', etc.

InjectRepository Decorator From @nestjs/typeorm:

The '@nestjs/typeorm'(NestJS library) provides 'InjectRepository' decorator. This 'InjectRepository' decorator helps to inject the 'Repository<TEntity>' from 'typeorm'(NodeJS library) into the service files constructor of our application.

Create EmployeeService:

In general, all our logical code will be implemented in our 'service' files.
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

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:

Now in service using the repository, we are going to query the PostgreSQL relational database. Repository from 'typeorm'(NodeJS library) is built with a predefined query method which makes our logic simple and easy for database communication. Now here we will implement the method to fetch all our employee data.
import { Employee } from './employee.entity';
// code hidden for display purpose
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:

Now let's add the Employee controller for our sample application. Create an endpoint to read all the employees from the PostgreSQL relational database.
import { Controller, Get } from '@nestjs/common';
import {EmployeeService} from './employee.service';
import {Employee} from './employee.entity';

export class EmployeeController {
    constructor(private readonly employeeService: EmployeeService){}

    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:

In NestJS implementation each business logic will be developed as simple separate modules. These Modules acts entry point to register all configuration like 'controllers', 'services', 'entities', etc. So here we need to create an Employee module for our business.
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';

  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:

Now to load or expose the child modules in an application we need to import those child modules in the app.module.ts file.
import { EmployeeModule } from './Employee/employee.module';

// code hidden for display purpose
  imports: [
export class AppModule {}
Now start the application and access the newly created endpoint and output shows as below.

Create Operation:

Now we are going to implement a create operation to create new employees.
'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.

Now in the controller let's add a post-action method.
import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common';

createEmployee(@Body() newEmployee:any){
  • '@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:

Add the following code to update a record.
'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.
updateEmployee(@Body() employeeToUpdate:any){

Delete Operation:

'delete()' method of 'Repository' from 'typeorm'. Bypassing the primary key id is enough to remove the record from the database.
deleteEmployee(@Param('id') id){
  • '@Delete()' route handler decorator. Routes Http Delete requests to the specified path.
  • '@Param()' this decorator is to extract the data from the route.

Wrapping Up:

Hopefully, I think this article delivered some useful information on creating a sample of NestJS CRUD operations using the relational database PostgreSQL. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


Popular posts from this blog

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route.

An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below
app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaults:new { …

GraphQL API Integration In Asp.Net Core Application

GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions.HTTP-POST is the only Http verb recommended by the GraphQL.The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API:The main building blocks of GraphQL API is Schemas and Types. A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc.Types likely to be called Grap…

ASP.NET Core Web API Versioning

Introduction: An iteration and evolutionary changes of an ASP.NET Core Web API is handled by Versioning. Versioning of an API gives confidence to the clients which consumes API for a long time. Any changes or development of an API will be accessible using the new version and it won't cause issues to the clients consuming the old version of API.
When To Use Versioning:Any API response changes.Developing an API by implementing testing levels like 'Alpha', 'Beta', and 'RC' versions before releasing Production.Deprecating an API which means API going to be removed or upgraded by a version within a short period. Versioning Types:Query String VersioningUrl Path VersioningMedia Type Versioning API Version Nuget: To Configure versioning to AspNet Core Web API Microsoft provided a library(Microsoft.AspNetCore.Mvc.Versioning). So to use the versioning library please install NuGet below.
 Install-Package Microsoft.AspNetCore.Mvc.Versioning -version 4.0.0 Register API V…

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload:The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client. Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file. Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk. If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application.
Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.  Check the link to use the Visual Studio Code for .NET Core Application.
IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files from the client, then the entire …

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items.
The main building block of ion-picker as follows: PickerControllerPickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options
PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker.
Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger", "Lion", "Elephant"…

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library jQuery Validate.
In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples.
Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio.
Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as below.
PersonController.cs: us…

Blazor WebAssembly Dynamic Form Validation

Introduction: In Blazor WebAssembly(client-side framework) form validation can be done with Data Annotations. Using Data Annotations we can validate form either by default validation attributes or by creating custom validation attributes. Using this Data Annotation attribute we can dynamically add or remove validation on a specific field in a form.
Create Blazor WebAssembly Project: To create a Blazor WebAssembly template project need to install the latest version of VisualStudio 2019 for rich intelligence support or we can use VisualStudio code but less intelligence support from the editor. Click here to know about Blazor WebAssembly template creation. Blazor WebAssembly is in preview mode, not yet ready for production.
Create Razor Component: After creating a sample project using the Blazor WebAssembly template, in "Pages" folder add new Razor Component, name it as "UserForm.razor"
Add Route: In Blazor routing can be configured using @page  directive, and URL should b…

Blazor Server CRUD Operations

Introduction: Blazor Server is a web framework to develop server-side single-page applications. Blazor is made up of components with the combinations on C#, Html, CSS.  Blazor Server is production-ready from the .Net Core 3.0.  Blazor Server Working Mechanism:Blazor Server is a very light-weight web development framework. In Blazor Server, not all code gets downloaded to the client browsers. Blazor Server made of components these components can be a block of code or page with respective navigation. Blazor server application communicates with the server with a SignalR background connection which is inbuilt functionality. Application click,  form submission, change events, application page navigation every operation is carried out by the SignalR connection by communicating with the server. Blazor updates the Html DOM very gently on every data update without any overhead. Blazor Server application maintains a nice intelligent tree structure to update the required information or changed …

NestJS API CRUD Operations With MongoDB

Introduction: NestJS is a framework used to develop server-side applications. NestJS built on top of Node.js frameworks like Express. It is a combination of Progressive Javascript, Object-Oriented Programming, Functional Programming, and Functional Reactive Programming.
Nest CLI Installation: Using Nest CLI we are able to generate the NestJS starter project with the default template. To install Nest CLI globally over our system open command prompt and run the command
npm i -g @nestjs/cli Now create a sample project by using Nest CLI command  nest new your_project_name package.json: Now open the package.json file from the sample application created, you can observe few properties like "scripts", "dependencies", and "devDependencies".
"dependencies" contains all plugins to be installed and used them to run the application.
"devDependencies" contain all plugins to be installed and used them at the time of application development.

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server.
Main Response Caching Headers are like below
Cache-ControlPragmaVary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response.private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores.max-age - this directive represents a time to hold a response in the - this directive represents no storing of response and always fetch the fresh response from serverno-store…