DEV Community

Cover image for Nest JS for Beginners #2: NestJS Sequelize PostgreSQL Configuration.
Mithun
Mithun

Posted on

Nest JS for Beginners #2: NestJS Sequelize PostgreSQL Configuration.

1 – NestJS Sequelize Package Installation

First step is to install the required dependencies.

Use the below npm install commands for the same:

$ npm install --save @nestjs/sequelize sequelize sequelize-typescript pg

$ npm install --save-dev @types/sequelize

Since, we are dealing with PostgreSQL, we install the pg package. If we were using MySQL, we need to use the mysql2 package.
We will be able to access our PostgreSQL server on port 5432.

2 – NestJS Sequelize PostgreSQL Configuration

Now that the setup part is out of the way, we can start focusing on writing the actual application.

The first step is to establish the connection between our application and the database. We can do so by adding the necessary configuration in the app.module.ts.

app.module.ts

Image description

We use the forRoot() method to supply the necessary configuration. Basically, the forRoot() method supports all the configuration parameters that are part of the Sequelize constructor.
It is useful have the autoLoadModels turned on. This actually helps create the schema and tables in the PostgreSQL during application start-up. Also, by using this option, we need not manually specify the models within our application context. NestJS will automatically scan our application code and find the classes decorated with the @Table annotation.

3 – Creating the Sequelize Model

The next step is to create the Sequelize Model class. Sequelize basically uses the Active Record pattern. In other words, you can directly use the model classes to interact with the database.

We will create one model to demonstrate the format.

book.model.ts

Image description

As you can see, the Book class extends the Sequelize Model class. Also, we use decorators such as @Table and @Column to define the various aspects of our model class.

Since we are creating a Library application, we will keep the model classes within a directory named library. Basically, we are trying to keep domain classes closer to the domain. In this case, the domain is the LibraryModule.

4 – Creating the Library Module

Let’s create the LibraryModule as well.

library.module.ts

Image description

This module uses the forFeature() method to define which models are registered in the current context. Also, we specify the LibraryService as a provider and LibraryController as a controller. We will get to those in the next section.

Also, we have already imported the Library Module in the app.module.ts file of the application.

5 – Creating the Service and Controller

The next step is to finally create the service (or provider) and the controller.

We have detailed posts on NestJS Providers and NestJS Controllers in case you want to know more about them. However, for the purpose of this post, we will create simplified versions.

Below is the service class.
library.service.ts

Image description

Below is the controller class
library.controller.ts

Image description

Interaction:

Controller Definition:

The LibraryController class is defined with various HTTP route handlers (e.g., createBook, fetchAll, findById).
It uses decorators like @Controller to define the base route for all its endpoints (/books in this case).

@Controller('books')
export class LibraryController {

constructor(private readonly libraryService: LibraryService) {}

}

Dependency Injection:

The LibraryController has a constructor that takes an instance of LibraryService as a parameter. NestJS injects an instance of LibraryService into the controller when an instance of LibraryController is created.

constructor(private readonly libraryService: LibraryService) {}
Calling Service Methods:
Inside the methods of LibraryController, you can see calls to methods of the injected LibraryService. For example, in the createBook method, it calls this.libraryService.createBook(book).

@post()

async createBook(@Res() response, @Body() book: Book) {

const newBook = await this.libraryService.createBook(book);

return response.status(HttpStatus.CREATED).json({newBook
});

}

Service Logic:
The actual logic for creating, fetching, or finding a book resides in the LibraryService. For example, the createBook method in LibraryService interacts with the Sequelize model (this.bookModel.create(book)) to perform the database operation.

@Injectable()

export class LibraryService {

constructor(@InjectModel(Book) private bookModel: typeof Book) {}

async createBook(book: Book): Promise { return this.bookModel.create(book);
}

}

Flow Summary:

When a request hits an endpoint handled by LibraryController (e.g., POST /books), the corresponding method in LibraryController is called.

The controller method processes the request, and if necessary, it delegates the actual logic to methods in LibraryService.
The service methods interact with data (e.g., database operations) or perform other business logic.

The result is then returned to the controller, which sends the appropriate response to the client.

If we start the application now, we can access the API endpoints at http://localhost:6000/books to create a book and then fetch the records from the database.
Image description

Image description

Image description

Image description

With this, we have successfully completed the NestJS Sequelize PostgreSQL integration. We have looked at the various configuration options and created appropriate request handlers to create and read data.

Top comments (0)