IP/3_Lab/testBootstrap_main/js/lines-rest-api.js

104 lines
3.5 KiB
JavaScript
Raw Normal View History

2023-11-16 13:21:52 +04:00
// модуль для работы с REST API сервера
// адрес сервера
const serverUrl = "http://localhost:8081";
// функция возвращает объект нужной структуры для отправки на сервер
function createLineObject(id, name, autor, number, annotation, info, image) {
return {
id : id,
name : name,
autor: autor,
info: info,
annotation: annotation,
number: number,
cover: image
};
}// модуль для работы с REST API сервера
// обращение к серверу для получения всех типов товара (get)
export async function getAllItemTypes() {
const response = await fetch(`${serverUrl}/items/`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для получения всех записей (get)
export async function getAllLines() {
const response = await fetch(`${serverUrl}/items`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для получения записи по первичному ключу (id) (get)
// id передается в качестве части пути URL get-запроса
export async function getLine(id) {
const response = await fetch(`${serverUrl}/lines/${id}?_expand=items`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для создания записи (post)
// объект отправляется в теле запроса (body)
export async function createLine(name, autor, number, annotation, info, image) {
const itemObject = createLineObject(name, autor, number, annotation, info, image);
const options = {
method: "POST",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/items`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для обновления записи по id (put)
// объект отправляется в теле запроса (body)
// id передается в качестве части пути URL get-запроса
export async function updateLine(id, name, autor, number, annotation, info, image) {
const itemObject = createLineObject(id, name, autor, number, annotation, info, image);
const options = {
method: "PUT",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/items/${id}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для удаления записи по id (delete)
// id передается в качестве части пути URL get-запроса
export async function deleteLine(id) {
const options = {
method: "DELETE",
};
const response = await fetch(`${serverUrl}/items/${id}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}