Creating 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
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Секція 1. Розділ 22