/
AchDoA
/
lab
Обзор
Документация
Войти
/
AchDoA
/
lab
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
module_3.1/services/postsService.js
89 строк
2 KB
AoDhcA
Add postsService.js: Implement functions to fetch, create, and update posts from the JSONPlaceholder API. Includes error handling and detailed JSDoc comments for better documentation and usability.
07 апр 2026, 19:07
07 апр 2026, 19:07
753ff72
Код
Авторство
О чём код?
const BASE_URL = 'https://jsonplaceholder.typicode.com/posts'; /** * Fetches all posts. * @returns {Promise<Array<{ userId: number, id: number, title: string, body: string }>>} */ export async function fetchPosts() { const response = await fetch(BASE_URL, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } /** * Fetches a single post by ID. * @param {number} id - Post ID. * @returns {Promise<{ userId: number, id: number, title: string, body: string }>} */ export async function fetchPostById(id) { const response = await fetch(`${BASE_URL}/${id}`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } /** * Creates a new post. * @param {{ title: string, body: string, userId: number }} postData - Post payload. * @returns {Promise<{ id: number, title: string, body: string, userId: number }>} */ export async function createPost(postData) { const response = await fetch(BASE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } /** * Partially updates a post by ID. * @param {number} id - Post ID. * @param {Partial<{ title: string, body: string, userId: number }>} updateData - Fields to update. * @returns {Promise<{ userId: number, id: number, title: string, body: string }>} */ export async function updatePost(id, updateData) { const response = await fetch(`${BASE_URL}/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(updateData), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } // Example usage: // fetchPosts(); // fetchPostById(1); // createPost({ title: 'foo', body: 'bar', userId: 1 }); // updatePost(1, { title: 'updated title' });