Afanasev_Stepan_PIbd-21_IP/ИП 3 лаба/js/lines-rest-api.js

94 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-01-10 16:11:49 +04:00
const serverUrl = "http://localhost:8081";
export async function getAllItemTypes() {
const response = await fetch(`${serverUrl}/items`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
export async function getAllActions() {
const response = await fetch(`${serverUrl}/actions`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
export async function getLine(id) {
const response = await fetch(`${serverUrl}/lines/${id}?_expand=items`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
export async function getAllLines() {
const response = await fetch(`${serverUrl}/lines?_expand=items&_expand=actions`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
function createLineObject(item, action, price, nick, duration, image) {
return {
itemsId: item,
actionsId: action,
price: parseFloat(price).toFixed(2),
nick,
duration,
image,
};
}
export async function createLine(item, action, price, nick, duration, image) {
const itemObject = createLineObject(item, action, price, nick, duration, 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();
}
export async function updateLine(id, item, action, price, nick, duration, image) {
const itemObject = createLineObject(item, action, price, nick, duration, 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();
}
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();
}