Kryukov_A.I_PIbd-21_IP/lab_3/js/apiendpoint.js

115 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-12-22 06:24:28 +04:00
const serverUrl = "http://localhost:8081";
export function createUserObject(
firstName,
lastName,
birthday,
address,
username,
password,
avatarImg,
) {
return {
firstName,
lastName,
birthday,
address,
username,
password,
avatarImg,
};
}
export function createPostObject(
userId,
createdDateTime,
text,
img,
) {
return {
userId,
createdDateTime,
text,
img,
};
}
export class ApiEndpoint {
constructor(endpoint) {
this.endpoint = endpoint;
}
async getObjects() {
const response = await fetch(`${serverUrl}/${this.endpoint}`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
async getObject(id) {
const response = await fetch(`${serverUrl}/${this.endpoint}/${id}`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
async createObject(obj) {
const options = {
method: "POST",
body: JSON.stringify(obj),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
try {
const response = await fetch(`${serverUrl}/${this.endpoint}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
} catch (error) {
console.error('Ошибка при выполнении запроса:', error);
throw error;
}
}
async updateObject(obj) {
const options = {
method: "PUT",
body: JSON.stringify(obj),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(
`${serverUrl}/${this.endpoint}/${obj.id}`,
options,
);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
async deleteObject(id) {
const options = {
method: "DELETE",
};
const response = await fetch(
`${serverUrl}/${this.endpoint}/${id}`,
options,
);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
}