Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating a Complete CRUD API Part Two | Error Handling and Final API
Building Backend Applications with Nest.js

bookCreating a Complete CRUD API Part Two

Stryg for at vise menuen

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.

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 6. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 6. Kapitel 3
some-alt