Kā tiek īstenots CRUD?
sobes.tech AI
Atbilde no AI
CRUD nozīmē Create, Read, Update, Delete. Tie ir galvenie operācijas, kas veicamas ar datiem.
Create (Izveidot): Sūtīt pieprasījumu ar POST metodi uz galapunktu, lai izveidotu jaunu resursu. Pieprasījuma ķermenis parasti satur jauna objekta datus.
// Piemēri ar Fetch API
fetch('/api/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'New Item' }),
})
.then(response => response.json())
.then(data => console.log('Izveidots:', data));
Read (Lasīt): Sūtīt pieprasījumu ar GET metodi:
- Visu resursu lasīšana: GET pieprasījums uz galveno kolekcijas galapunktu.
- Konkrēta resursa lasīšana: GET pieprasījums ar resursa identifikatoru.
// Lasīt visus
fetch('/api/items')
.then(response => response.json())
.then(data => console.log('Visi elementi:', data));
// Lasīt konkrētu
fetch('/api/items/123')
.then(response => response.json())
.then(data => console.log('Elements 123:', data));
Update (Atjaunināt): Sūtīt pieprasījumu ar PUT vai PATCH metodi uz resursa galapunktu ar identifikatoru:
- PUT: pilnīga esošā resursa aizstāšana.
- PATCH: daļēja atjaunināšana.
// Atjaunināt (PUT)
fetch('/api/items/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Updated Item' }),
})
.then(response => response.json())
.then(data => console.log('Atjaunināts:', data));
// Daļēja atjaunināšana (PATCH)
fetch('/api/items/123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ description: 'New Description' }),
})
.then(response => response.json())
.then(data => console.log('Pārbūvēts:', data));
Delete (Dzēst): Sūtīt pieprasījumu ar DELETE metodi uz resursa galapunktu ar identifikatoru:
fetch('/api/items/123', {
method: 'DELETE',
})
.then(response => {
if (response.ok) {
console.log('Veiksmīgi dzēsts');
} else {
console.error('Dzēšana neizdevās');
}
});
Saites ar REST API:
CRUD operācijas cieši saistītas ar REST (Representational State Transfer) principiem, kur HTTP metodes tiek izmantotas šo darbību veikšanai resursiem:
| CRUD | HTTP Metode |
|---|---|
| Create | POST |
| Read | GET |
| Update | PUT/PATCH |
| Delete | DELETE |
Frontendā CRUD realizācija ietver šo HTTP pieprasījumu sūtīšanu uz backend API un saņemto atbilžu apstrādi. Bieži tiek izmantotas HTTP bibliotēkas (piemēram, Axios, Fetch API) un ietvari/bibliotēkas stāvokļa un UI pārvaldībai (piemēram, React, Vue, Angular).