Creating a Complete CRUD API Part One
Svep för att visa menyn
Now you will combine several Nest.js concepts and start building a small CRUD API.
CRUD stands for:
- Create;
- Read;
- Update;
- Delete.
In this part, you will set up a simple users API with routes for creating users and getting all users.
Start with the service:
import { Injectable } 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;
}
}
Here is what is happening:
users: stores the current list of users;getAllUsers(): returns all users;createUser(): creates a new user and adds it to the array.
Now update the controller:
import { Controller, Get, Post, 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);
}
}
Here is what is happening:
@Get(): returns all users;@Post(): creates a new user;@Body(): gets data from the request body;- The controller passes the work to the service.
With this setup, your API can already:
- Return all users;
- Create a new user.
This is the first half of a CRUD API.
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 21
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Avsnitt 1. Kapitel 21