Home > Web Front-end > JS Tutorial > NestJs CRUD Operations Example

NestJs CRUD Operations Example

Emily Anne Brown
Release: 2025-03-07 18:43:15
Original
469 people have browsed it

NestJS CRUD Operations Example

This example demonstrates a basic CRUD (Create, Read, Update, Delete) operation for a Cat entity using NestJS. We'll utilize TypeORM for database interaction. Assume you have a Cat entity defined as follows:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class Cat {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  age: number;
}
Copy after login

Now, let's create a cats.controller.ts file:

import { Controller, Get, Post, Body, Param, Delete, Put } from '@nestjs/common';
import { CreateCatDto } from './create-cat.dto';
import { Cat } from './cat.entity';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
    return this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }

  @Get(':id')
  async findOne(@Param('id') id: string): Promise<Cat> {
    return this.catsService.findOne(+id);
  }

  @Put(':id')
  async update(@Param('id') id: string, @Body() updateCatDto: CreateCatDto): Promise<Cat> {
    return this.catsService.update(+id, updateCatDto);
  }

  @Delete(':id')
  async remove(@Param('id') id: string): Promise<void> {
    return this.catsService.remove(+id);
  }
}
Copy after login

And a corresponding cats.service.ts:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cat } from './cat.entity';
import { CreateCatDto } from './create-cat.dto';

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cat)
    private catsRepository: Repository<Cat>,
  ) {}

  async create(cat: CreateCatDto): Promise<Cat> {
    const newCat = this.catsRepository.create(cat);
    return this.catsRepository.save(newCat);
  }

  async findAll(): Promise<Cat[]> {
    return this.catsRepository.find();
  }

  async findOne(id: number): Promise<Cat> {
    return this.catsRepository.findOneBy({ id });
  }

  async update(id: number, cat: CreateCatDto): Promise<Cat> {
    await this.catsRepository.update(id, cat);
    return this.catsRepository.findOneBy({ id });
  }

  async remove(id: number): Promise<void> {
    await this.catsRepository.delete(id);
  }
}
Copy after login

Remember to install necessary packages: npm install @nestjs/typeorm typeorm and configure your database connection in your ormconfig.json. This provides a complete, albeit basic, CRUD example.

How can I implement basic CRUD operations using NestJS?

Implementing basic CRUD operations in NestJS typically involves these steps:

  1. Define your Entity: Create a TypeScript class representing your data model using TypeORM decorators (@Entity, @PrimaryGeneratedColumn, @Column, etc.). This defines the structure of your data in the database.
  2. Create a Service: This layer handles the business logic for interacting with your data. It uses a repository (typically provided by TypeORM) to perform database operations. The service encapsulates data access logic, allowing the controller to remain clean and focused on request handling.
  3. Create a Controller: This layer handles incoming HTTP requests (POST, GET, PUT, DELETE) and delegates the actual data manipulation to the service. NestJS decorators (@Controller, @Get, @Post, @Put, @Delete, @Body, @Param) are used to map HTTP requests to controller methods.
  4. Use a Repository (e.g., TypeORM): A repository provides an abstraction layer for database interaction. It handles database-specific operations, allowing your service to remain independent of the underlying database technology. TypeORM is a popular choice, offering features like automatic schema generation and migrations.
  5. Data Transfer Objects (DTOs): Create DTOs to validate and structure the data received from HTTP requests. This enhances security and improves code readability.

What are the best practices for structuring a NestJS application with CRUD functionalities?

Several best practices improve the maintainability and scalability of your NestJS application:

  • Modular Design: Organize your code into modules based on functionality (e.g., user module, product module). This improves code organization and reusability.
  • Separation of Concerns: Strictly separate concerns between controllers (handling requests), services (business logic), and repositories (data access).
  • Use DTOs: Always use DTOs to validate and shape incoming and outgoing data. This improves security and data consistency.
  • Input Validation: Validate user inputs using class-validator or similar libraries to prevent invalid data from reaching your database.
  • Error Handling: Implement robust error handling mechanisms to gracefully handle exceptions and return appropriate HTTP status codes.
  • Testing: Write unit and integration tests to ensure the correctness and reliability of your code.
  • Versioning: Consider implementing API versioning to manage changes to your API over time.

What are some common pitfalls to avoid when building CRUD operations in NestJS?

Common pitfalls to avoid include:

  • Insufficient Input Validation: Failing to validate user input can lead to security vulnerabilities (e.g., SQL injection) and data inconsistencies.
  • Ignoring Error Handling: Lack of proper error handling can lead to application crashes or unexpected behavior. Always handle potential exceptions and return meaningful error messages.
  • Mixing Business Logic in Controllers: Controllers should primarily focus on routing requests. Complex business logic should reside in services.
  • Direct Database Access in Controllers: Controllers should never directly interact with the database. Always use a service and repository layer.
  • Overly Complex Controllers: Keep controllers lean and focused. Large, complex controllers are difficult to maintain and test.
  • Lack of Testing: Insufficient testing can lead to bugs and regressions. Write unit tests for services and integration tests for controllers and repositories.
  • Ignoring Pagination and Filtering: For large datasets, implement pagination and filtering to improve performance and user experience. Don't retrieve the entire dataset for every request.

The above is the detailed content of NestJs CRUD Operations Example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template