Skip to content

Example Code

A sample code to learn CRUD operations using nestjs with MySQL.

Setting Up the Project

Terminal window
npm i -g @nestjs/cli
nest new backend

This creates a new directory called backend

Terminal window
cd backend
Install Dependencies
Terminal window
npm i @nestjs/sequelize
npm i class-transformer
npm i class-validator
npm i mysql2
npm i sequelize
npm i sequelize-typescript
npm i --save-dev @types/sequelize

Start Coding

create required resource

For quickly creating a CRUD controller Run nest g resource books .

  • Directorybackend
    • Directorysrc
      • Directorybooks
        • books.module.ts
        • books.controller.ts
        • books.service.ts
      • app.controller.spec.ts
      • app.controller.ts
      • app.module.ts
      • app.service.ts
      • main.ts
configure DB -mysql

create book.model.ts in your /books/model/ directory .
create a .env file and add env-variables

host = "";
user = "";
password = "";
db_name = "";
import { Column, Model, Table } from 'sequelize-typescript';
@Table
export class Book extends Model {
@Column({ autoIncrement: true, primaryKey: true, allowNull: false })
book_id: number;
@Column({ allowNull: false })
title: string;
@Column({ allowNull: false })
subject: string;
@Column({ allowNull: false })
author: string;
@Column({ allowNull: false })
available: number;
@Column({ allowNull: false })
image_url: string;
}
CRUD operations

Create a book.dto.ts in your /books/dto/ directory .

book.dto.ts
import { IsOptional, IsString, IsNotEmpty, IsInt } from 'class-validator';
export class BookDto {
@IsOptional()
@IsInt()
book_id: number;
@IsNotEmpty({ message: 'title required' })
@IsString()
title: string;
@IsString()
@IsNotEmpty({ message: 'please provide subject' })
subject: string;
@IsString()
@IsNotEmpty({ message: 'Auther is required' })
author: string;
@IsInt()
available: number;
@IsString()
image_url: string;
}
export class BookUpdateDto {
@IsOptional()
@IsInt()
book_id: number;
@IsInt()
available: number;
}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

Run and Test the App

Start the Server

Run the server:

Terminal window
nest start --watch

Use Postman or any REST client to test your API .