SQL (Sequelize)

This chapter applies only to TypeScript

Warning In this article, you’ll learn how to create a DatabaseModule based on the Sequelize package from scratch using custom components. As a consequence, this technique contains a lot of overhead that you can avoid by using the dedicated, out-of-the-box @nestjs/sequelize package. To learn more, see here.

Sequelize is a popular Object Relational Mapper (ORM) written in a vanilla JavaScript, but there is a sequelize-typescript TypeScript wrapper which provides a set of decorators and other extras for the base sequelize.

Getting started

To start the adventure with this library we have to install the following dependencies:

  1. $ npm install --save sequelize sequelize-typescript mysql2
  2. $ npm install --save-dev @types/sequelize

The first step we need to do is create a Sequelize instance with an options object passed into the constructor. Also, we need to add all models (the alternative is to use modelPaths property) and sync() our database tables.

  1. @@filename(database.providers)
  2. import { Sequelize } from 'sequelize-typescript';
  3. import { Cat } from '../cats/cat.entity';
  4. export const databaseProviders = [
  5. {
  6. provide: 'SEQUELIZE',
  7. useFactory: async () => {
  8. const sequelize = new Sequelize({
  9. dialect: 'mysql',
  10. host: 'localhost',
  11. port: 3306,
  12. username: 'root',
  13. password: 'password',
  14. database: 'nest',
  15. });
  16. sequelize.addModels([Cat]);
  17. await sequelize.sync();
  18. return sequelize;
  19. },
  20. },
  21. ];

info Hint Following best practices, we declared the custom provider in the separated file which has a *.providers.ts suffix.

Then, we need to export these providers to make them accessible for the rest part of the application.

  1. import { Module } from '@nestjs/common';
  2. import { databaseProviders } from './database.providers';
  3. @Module({
  4. providers: [...databaseProviders],
  5. exports: [...databaseProviders],
  6. })
  7. export class DatabaseModule {}

Now we can inject the Sequelize object using @Inject() decorator. Each class that would depend on the Sequelize async provider will wait until a Promise is resolved.

Model injection

In Sequelize the Model defines a table in the database. Instances of this class represent a database row. Firstly, we need at least one entity:

  1. @@filename(cat.entity)
  2. import { Table, Column, Model } from 'sequelize-typescript';
  3. @Table
  4. export class Cat extends Model {
  5. @Column
  6. name: string;
  7. @Column
  8. age: number;
  9. @Column
  10. breed: string;
  11. }

The Cat entity belongs to the cats directory. This directory represents the CatsModule. Now it’s time to create a Repository provider:

  1. @@filename(cats.providers)
  2. import { Cat } from './cat.entity';
  3. export const catsProviders = [
  4. {
  5. provide: 'CATS_REPOSITORY',
  6. useValue: Cat,
  7. },
  8. ];

warning Warning In the real-world applications you should avoid magic strings. Both CATS_REPOSITORY and SEQUELIZE should be kept in the separated constants.ts file.

In Sequelize, we use static methods to manipulate the data, and thus we created an alias here.

Now we can inject the CATS_REPOSITORY to the CatsService using the @Inject() decorator:

  1. @@filename(cats.service)
  2. import { Injectable, Inject } from '@nestjs/common';
  3. import { CreateCatDto } from './dto/create-cat.dto';
  4. import { Cat } from './cat.entity';
  5. @Injectable()
  6. export class CatsService {
  7. constructor(
  8. @Inject('CATS_REPOSITORY')
  9. private catsRepository: typeof Cat
  10. ) {}
  11. async findAll(): Promise<Cat[]> {
  12. return this.catsRepository.findAll<Cat>();
  13. }
  14. }

The database connection is asynchronous, but Nest makes this process completely invisible for the end-user. The CATS_REPOSITORY provider is waiting for the db connection, and the CatsService is delayed until repository is ready to use. The entire application can start when each class is instantiated.

Here is a final CatsModule:

  1. @@filename(cats.module)
  2. import { Module } from '@nestjs/common';
  3. import { CatsController } from './cats.controller';
  4. import { CatsService } from './cats.service';
  5. import { catsProviders } from './cats.providers';
  6. import { DatabaseModule } from '../database/database.module';
  7. @Module({
  8. imports: [DatabaseModule],
  9. controllers: [CatsController],
  10. providers: [
  11. CatsService,
  12. ...catsProviders,
  13. ],
  14. })
  15. export class CatsModule {}

info Hint Do not forget to import the CatsModule into the root AppModule.