InternetProgramming/Lab3/js/lines-rest-api.js
2023-11-30 18:13:57 +03:00

100 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// модуль для работы с REST API сервера
// адрес сервера
const serverUrl = "http://localhost:8081";
// Функция создания объекта-игры для отправки на сервер
function createLineObject(genre, name, price, image) {
return {
genresId: genre,
name,
price: Math.floor(parseFloat(price)),
image,
};
}
// Обращение к серверу для получения всех жанров (get)
export async function getAllGenreTypes() {
const response = await fetch(`${serverUrl}/genres`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// Обращение к серверу для получения всех игр (get)
export async function getAllLines() {
const response = await fetch(`${serverUrl}/lines?_expand=genres`);
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=genres`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// Обращение к серверу для создания записи (post)
// объект отправляется в теле запроса (body)
export async function createLine(genre, name, price, image) {
const itemObject = createLineObject(genre, name, price, image);
const options = {
method: "POST",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/lines`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// Обращение к серверу для обновления записи по id (put)
// объект отправляется в теле запроса (body)
// id передается в качестве части пути URL get-запроса
export async function updateLine(id, genre, name, price, image) {
const itemObject = createLineObject(genre, name, price, image);
const options = {
method: "PUT",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/lines/${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}/lines/${id}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}