Sobes.tech
Junior

როგორ ხორციელდება CRUD?

sobes.tech AI

პასუხი AI-სგან

CRUD යනු Create, Read, Update, Delete යන අර්ථයන් වේ. මෙය දත්ත මත සිදුකෙරෙන මූලික මෙහෙයුම් වේ.

Create (සෑදීම): නව සම්පතක් නිර්මාණය කිරීමට POST ක්‍රමය භාවිතා කර එන්ඩ්පොයින්ට යැවීම. ඉල්ලීමේ ශරීරය සාමාන්‍යයෙන් නව වස්තුවේ දත්ත අඩංගු වේ.

// 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('නිර්මාණය විය:', data));

Read (කියවීම): GET ක්‍රමය භාවිතා කර ඉල්ලීම යැවීම:

  • සියලු සම්පත් කියවීම: මූලික එකතුවේ අන්තර්ගතයට GET ඉල්ලීම.
  • නියමිත සම්පතක් කියවීම: සම්පතේ හැඳුනුම්පත සමඟ අන්තර්ගතයට GET ඉල්ලීම.
// සියල්ල කියවීම
fetch('/api/items')
  .then(response => response.json())
  .then(data => console.log('සියලු අයිතම:', data));

// නියමිත එකක් කියවීම
fetch('/api/items/123')
  .then(response => response.json())
  .then(data => console.log('අයිතම 123:', data));

Update (යාවත්කාලීන කිරීම): PUT හෝ PATCH ක්‍රමය භාවිතා කර ඉල්ලීම යැවීම:

  • PUT: පූර්ණයෙන්ම පවත්නා සම්පත වෙනස් කිරීම.
  • PATCH: කොටස්වල යාවත්කාලීන කිරීම.
// යාවත්කාලීන කිරීම (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('යාවත්කාලීන විය:', data));

// කොටස්වල යාවත්කාලීන (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('පැච් කළා:', data));

Delete (මකීම): DELETE ක්‍රමය භාවිතා කර ඉල්ලීම යැවීම:

fetch('/api/items/123', {
  method: 'DELETE',
})
  .then(response => {
    if (response.ok) {
      console.log('සාර්ථකව මකන ලදි');
    } else {
      console.error('මකීම අසාර්ථක විය');
    }
  });

REST API සමඟ සම්බන්ධතාව:

CRUD මෙහෙයුම් REST (Representational State Transfer) මූලධර්මවලට සමීපව, මෙහිදී HTTP ක්‍රම භාවිතා කර මෙහෙයුම් සිදු කරයි:

CRUD HTTP ක්‍රමය
Create POST
Read GET
Update PUT/PATCH
Delete DELETE

ඉදිරිපස, CRUD ක්‍රියාවලියට මෙම HTTP ඉල්ලීම් යැවීම සහ ලැබෙන පිළිතුරු සැකසීම ඇතුළත් වේ. බොහෝවිට, HTTP සමඟ වැඩ කිරීමට පුස්තකාල (උදාහරණයක් ලෙස, Axios, Fetch API) සහ UI/තත්ව කළමනාකරණ රාමක (උදාහරණයක් ලෙස, React, Vue, Angular) භාවිතා වේ.