Creating a Complete CRUD API Part Two
Deslize para mostrar o menu
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.
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 1. Capítulo 22
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Seção 1. Capítulo 22