Example Code
A sample code to learn CRUD operations using nestjs with MySQL.
Setting Up the Project
npm i -g @nestjs/cli nest new backendThis creates a new directory called backend
Navigate to the Project Directory
cd backendInstall Dependencies
npm i @nestjs/sequelizenpm i class-transformernpm i class-validatornpm i mysql2npm i sequelizenpm i sequelize-typescriptnpm i --save-dev @types/sequelizeStart 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';@Tableexport 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;}@Module({imports: [ConfigModule.forRoot({isGlobal: true,}),SequelizeModule.forRoot({dialect: 'mysql',host: process.env.host,username: process.env.user,password: process.env.password,database: process.env.db_name,models: [Book],autoLoadModels: true,synchronize: true,}),BooksModule,],})@Module({imports: [SequelizeModule.forFeature([Book])],controllers: [BooksController],providers: [BooksService],})CRUD operations
Create a book.dto.ts in your /books/dto/ directory .
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();import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query,} from '@nestjs/common';import { BooksService } from './books.service';import { BookDto, BookUpdateDto } from './dto/book.dto';
@Controller()export class BooksController { constructor(private bookService: BooksService) {} @Get() async getAllBooks() { return await this.bookService.getAllBooks(); }
@Get('book/:id') async getBook(@Param('id', ParseIntPipe) id: number) { return await this.bookService.getBook(id); }
@Post('create') async createBook(@Body() body: BookDto) { return await this.bookService.addBook(body); }
@Put('book/update') async updateBook(@Body() body: BookUpdateDto) { return await this.bookService.updateCount(body.available, body.book_id); } @Delete('remove/:id') async removeBook(@Param('id', ParseIntPipe) id: number) { return await this.bookService.removeBook(id); }
@Get('search') async searchbooks(@Query('name') title: string) { return await this.bookService.findBookByName(title); }}import { Injectable } from '@nestjs/common';import { InjectModel } from '@nestjs/sequelize';import { Book } from './model/book.model';import { BookDto } from './dtos/book.dto';import { Op } from 'sequelize';
@Injectable()export class BooksService { constructor( @InjectModel(Book) private bookModel: typeof Book, ) {}
async addBook(book: BookDto) { try { return await this.bookModel.create({ title: book.title, subject: book.subject, author: book.author, available: book.available, image_url: book.image_url, }); } catch (error) { throw error; } }
async findBookByName(title: string) { try { // write your code } catch (error) { throw error; } }
async removeBook(id: number) { try { // write your code } catch (error) { throw error; } }
async getAllBooks() { try { // write your code } catch (error) { throw error; } } async updateCount(count: number, id: number) { try { return await this.bookModel.update( { available: count }, { where: { book_id: id } }, ); } catch (error) { throw error; } }
getBook(id: number) { try { return this.bookModel.findOne({ where: { book_id: id } }); } catch (error) { throw error; } }}Run and Test the App
Start the Server
Run the server:
nest start --watchUse Postman or any REST client to test your API .