Creating a Complete CRUD API Part One
Sveip for å vise menyen
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.
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 6. Kapittel 2
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Seksjon 6. Kapittel 2