Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Creating a Complete CRUD API Part Two | Section
Building Backend Applications with Nest.js

bookCreating a Complete CRUD API Part Two

メニューを表示するにはスワイプしてください

In this part, you will complete the CRUD API by adding routes for updating and deleting users.

First, update the service:

import { Injectable, NotFoundException } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
  ];

  getAllUsers() {
    return this.users;
  }

  createUser(user: { name: string; age: number }) {
    const newUser = {
      id: this.users.length + 1,
      ...user,
    };

    this.users.push(newUser);
    return newUser;
  }

  updateUser(id: number, updatedUser: { name: string; age: number }) {
    const user = this.users.find(user => user.id === id);

    if (!user) {
      throw new NotFoundException('User not found');
    }

    user.name = updatedUser.name;
    user.age = updatedUser.age;

    return user;
  }

  deleteUser(id: number) {
    const userIndex = this.users.findIndex(user => user.id === id);

    if (userIndex === -1) {
      throw new NotFoundException('User not found');
    }

    const deletedUser = this.users[userIndex];
    this.users.splice(userIndex, 1);

    return deletedUser;
  }
}

Here is what is happening:

  • updateUser(): finds a user by ID and updates the data;
  • deleteUser(): finds a user by ID and removes it from the array;
  • NotFoundException: returns an error if the user does not exist.

Now update the controller:

import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
import { UsersService } from './users.service';

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

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }

  @Post()
  createUser(@Body() body: { name: string; age: number }) {
    return this.usersService.createUser(body);
  }

  @Put(':id')
  updateUser(
    @Param('id') id: string,
    @Body() body: { name: string; age: number }
  ) {
    return this.usersService.updateUser(Number(id), body);
  }

  @Delete(':id')
  deleteUser(@Param('id') id: string) {
    return this.usersService.deleteUser(Number(id));
  }
}

Here is what is happening:

  • @Put(':id'): updates a user with a specific ID;
  • @Delete(':id'): deletes a user with a specific ID;
  • @Param('id'): gets the ID from the URL;
  • Number(id): converts the route parameter from string to number.

At this point, your API can create, read, update, and delete users.

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  22

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  22
some-alt