SQL (TypeORM)

This chapter applies only to TypeScript

Warning In this article, you’ll learn how to create a DatabaseModule based on the TypeORM package from scratch using custom providers mechanism. As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated @nestjs/typeorm package. To learn more, see here.

TypeORM is definitely the most mature Object Relational Mapper (ORM) available in the node.js world. Since it’s written in TypeScript, it works pretty well with the Nest framework.

Getting started

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

  1. $ npm install --save typeorm mysql

The first step we need to do is to establish the connection with our database using createConnection() function imported from the typeorm package. The createConnection() function returns a Promise, and therefore we have to create an async provider.

  1. @@filename(database.providers)
  2. import { createConnection } from 'typeorm';
  3. export const databaseProviders = [
  4. {
  5. provide: 'DATABASE_CONNECTION',
  6. useFactory: async () => await createConnection({
  7. type: 'mysql',
  8. host: 'localhost',
  9. port: 3306,
  10. username: 'root',
  11. password: 'root',
  12. database: 'test',
  13. entities: [
  14. __dirname + '/../**/*.entity{.ts,.js}',
  15. ],
  16. synchronize: true,
  17. }),
  18. },
  19. ];

warning 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 of the application.

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

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

Repository pattern

The TypeORM supports the repository design pattern, thus each entity has its own Repository. These repositories can be obtained from the database connection.

But firstly, we need at least one entity. We are going to reuse the Photo entity from the official documentation.

  1. @@filename(photo.entity)
  2. import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
  3. @Entity()
  4. export class Photo {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column({ length: 500 })
  8. name: string;
  9. @Column('text')
  10. description: string;
  11. @Column()
  12. filename: string;
  13. @Column('int')
  14. views: number;
  15. @Column()
  16. isPublished: boolean;
  17. }

The Photo entity belongs to the photo directory. This directory represents the PhotoModule. Now, let’s create a Repository provider:

  1. @@filename(photo.providers)
  2. import { Connection, Repository } from 'typeorm';
  3. import { Photo } from './photo.entity';
  4. export const photoProviders = [
  5. {
  6. provide: 'PHOTO_REPOSITORY',
  7. useFactory: (connection: Connection) => connection.getRepository(Photo),
  8. inject: ['DATABASE_CONNECTION'],
  9. },
  10. ];

warning Notice In the real-world applications you should avoid magic strings. Both PHOTO_REPOSITORY and DATABASE_CONNECTION should be kept in the separated constants.ts file.

Now we can inject the Repository<Photo> to the PhotoService using the @Inject() decorator:

  1. @@filename(photo.service)
  2. import { Injectable, Inject } from '@nestjs/common';
  3. import { Repository } from 'typeorm';
  4. import { Photo } from './photo.entity';
  5. @Injectable()
  6. export class PhotoService {
  7. constructor(
  8. @Inject('PHOTO_REPOSITORY')
  9. private readonly photoRepository: Repository<Photo>,
  10. ) {}
  11. async findAll(): Promise<Photo[]> {
  12. return await this.photoRepository.find();
  13. }
  14. }

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

Here is a final PhotoModule:

  1. @@filename(photo.module)
  2. import { Module } from '@nestjs/common';
  3. import { DatabaseModule } from '../database/database.module';
  4. import { photoProviders } from './photo.providers';
  5. import { PhotoService } from './photo.service';
  6. @Module({
  7. imports: [DatabaseModule],
  8. providers: [
  9. ...photoProviders,
  10. PhotoService,
  11. ],
  12. })
  13. export class PhotoModule {}

warning Hint Do not forget to import the PhotoModule into the root ApplicationModule.