Quick starter Nestjs CRUD Using TypeORM Mysql 💻 🎯

Build your First REST API CRUD App with TypeORM

In this tutorial, you will learn to build your first REST API CRUD application with Nestjs using the TypeORM as the ORM to abstract away the differences between the multiple DBMS. Here we are going to use the MySQL info for the CRUD application for currently.

Prerequisites

We are assuming that you have already:
A local development environment for Node.js. How to install Node.js and set up a local development environment and @nestjs/cli installed.

Creating a Nest.js Project

Run the below command to generate a project:

$ nest new nestjs_mysql_crud_app
$ cd nestjs_mysql_crud_app

STEP1: Creating a module

$ nest g module users

The command will create a src/users/users.module.ts file with some predefined code:

    import { Module } from '@nestjs/common';

    @Module({})
    export class UsersModule {}
    Since this was generated by the command so this module has also been added automatically to the src/app.module.ts. Now src/app.module.ts look likes:
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UsersModule } from './users/users.module'; 

    @Module({ imports: [UsersModule],
        controllers: [AppController],
        providers: [AppService],
    }) 
    export class AppModule {}

STEP2: Installing the required dependencies

As you know, today we will establish connectivity to the MySQL database here and for that we will use the TypeORM module (which holds the connector for MySQL database).

Now the question will arise in your mind that what will we have to do to do this? Nest.js supports TypeORM a Object Relational Mapper (ORM) available in TypeScript. It is available from the @nestjs/typeorm package. So run the following commands:

$ npm install mysql typeorm @nestjs/typeorm –save

After successfully installation you need to import the TypeOrmModule inside the ApplicationModule. Open the src/app.module.ts file and add the following changes:

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UsersModule } from './users/users.module';

    @Module({
      imports: [TypeOrmModule.forRoot(), UsersModule],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}

As you can see above, here we imported TypeOrmModule and that we use the forRoot() technique to pass a configuration object (this is that the same object that you simply would ordinarily pass to the quality createConnection() technique of TypeORM).

STEP3: Setup database connection configuration

We have installed the dependencies and also have added to the app module, but where is the database connection details? As per the TypeORM official documentation there are several connection options like ormconfig.json / ormconfig.js / ormconfig.yml / ormconfig.env / ormconfig.xml but in this tutorial we will use ormconfig.json method.

On the root of the project create a file ormconfig.json and add the following code in it: You can also register typeorm module dynamically by passing configuration from config module- check my other blog for dynamic registration of module

    {
      "type": "mysql",
      "host": "localhost",
      "port": "3306",
      "username": "root",
      "password": "root",
      "database": "nestjs_mysql_crud_app",
      "synchronize": false,
      "logging": true,
      "entities": ["src//*.entity.ts", "dist//*entity.ts"]
    }

Here field “entities” s a class that maps to a database table.

STEP4: Creating a TypeORM entity model

After configuring TypeORM module, let’s now create our first entity. Run the following command from the root of your project:

    $ touch src/users/users.entity.ts 

Now open the src/users/users.entity.ts and paste the following code in it:

    import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert } from 'typeorm';
    import * as crypto from 'crypto';
    @Entity('users')
    export class UsersEntity {
      @PrimaryGeneratedColumn()
      id: number;

      @Column()
      name: string;

      @Column()
      email: string;

      @BeforeInsert()
      hashPassword() {
        this.password = crypto.createHmac('sha256', this.password).digest('hex');
      }
      @Column()
      password: string;
    }

Next, open the src/users/users.module.ts file and update it as follows:

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { UsersController } from './users.controller';
    import { UsersService } from './users.service';
    import { UsersEntity } from './users.entity';

    @Module({
      imports: [TypeOrmModule.forFeature([UsersEntity])],
      controllers: [UsersController],
      providers: [UsersService],
    })
    export class UsersModule {}

Now, the time to speed up the things.

STEP5: Setting up a service

$ nest g service users

Open the src/users/users.service.ts file and paste the following code in it:

    import { Injectable, HttpStatus } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';

    import { UsersEntity } from './users.entity';
    import { UsersDTO } from './users.dto';

    @Injectable()
    export class UsersService {
      constructor(
        @InjectRepository(UsersEntity)
        private usersRepository: Repository<UsersEntity>,
      ) {}

      async showAll() {
        return await this.usersRepository.find();
      }

      async create(data: UsersDTO) {
        const user = this.usersRepository.create(data);
        await this.usersRepository.save(data);
        return user;
      }

      async findByEmail(email: string): Promise<UsersDTO> {
        return await this.usersRepository.findOne({
          where: {
            email: email,
          },
        });
      }

      async read(id: number) {
        return await this.usersRepository.findOne({ where: { id: id } });
      }

      async update(id: number, data: Partial<UsersDTO>) {
        await this.usersRepository.update({ id }, data);
        return await this.usersRepository.findOne({ id });
      }

      async destroy(id: number) {
        await this.usersRepository.delete({ id });
        return { deleted: true };
      }
    }

STEP6: Creating routes & controllers

$ nest g controller users

now open the src/users/users.controllers.ts and paste the following code in it:

    import {
      Controller,
      Get,
      Post,
      Patch,
      Delete,
      Body,
      Param,
      HttpStatus,
    } from '@nestjs/common';

    import { UsersService } from './users.service';
    import { UsersDTO } from './users.dto';

    @Controller('users')
    export class UsersController {
      constructor(private usersService: UsersService) {}

      @Get()
      async showAllUsers() {
        const users =  await this.usersService.showAll();
        return {
          statusCode: HttpStatus.OK,
          message: 'Users fetched successfully',
          users
        };
      }

      @Post()
      async createUsers(@Body() data: UsersDTO) {
         const user = await this.usersService.create(data);
        return {
          statusCode: HttpStatus.OK,
          message: 'User created successfully',
          user
        };
      }

      @Get(':id')
      async readUser(@Param('id') id: number) {
        const data =  await this.usersService.read(id);
        return {
          statusCode: HttpStatus.OK,
          message: 'User fetched successfully',
          data,
        };
      }

      @Patch(':id')
      async uppdateUser(@Param('id') id: number, @Body() data: Partial<UsersDTO>) {
        await this.usersService.update(id, data);
        return {
          statusCode: HttpStatus.OK,
          message: 'User updated successfully',
        };
      }

      @Delete(':id')
      async deleteUser(@Param('id') id: number) {
        await this.usersService.destroy(id);
        return {
          statusCode: HttpStatus.OK,
          message: 'User deleted successfully',
        };
      }
    }

STEP7: Create users data object model

Go to the root directory of the project and run the following command:

$ touch src/users/users.dto.ts

open the users.dto and paste the following code in it:

    export interface UsersDTO {
      id: number;
      name: string;
      email: string;
      password: string;
    }

Now, you are almost done to achieve your goal, open the src/users/users.module.ts file and register your UsersController, UsersService, and UsersEntity and your final code will be:

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm'
    import { UsersController } from './users.controller';
    import { UsersService } from './users.service';
    import { UsersEntity } from './users.entity';

    @Module({
      imports: [TypeOrmModule.forFeature([UsersEntity])],
      controllers: [UsersController],
      providers: [UsersService],
    })
    export class UsersModule {}

Now, start the application again (if running then stop first) using the following command:

$ npm run start

I hope, you did enjoy the tutorial and had an idea to create REST API CRUD application with Nestjs using the TypeORM (MySQL).

Comments