Initial commit
This commit is contained in:
commit
3857598de4
159 changed files with 14537 additions and 0 deletions
92
src/shared/utils/api.js
Normal file
92
src/shared/utils/api.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
/**
|
||||
* API utility functions for making HTTP requests
|
||||
*/
|
||||
|
||||
const DEFAULT_HEADERS = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
/**
|
||||
* Make a GET request
|
||||
* @param {string} url - API endpoint
|
||||
* @param {object} options - Fetch options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function get(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: { ...DEFAULT_HEADERS, ...options.headers },
|
||||
...options,
|
||||
});
|
||||
return handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a POST request
|
||||
* @param {string} url - API endpoint
|
||||
* @param {object} data - Request body
|
||||
* @param {object} options - Fetch options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function post(url, data, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { ...DEFAULT_HEADERS, ...options.headers },
|
||||
body: JSON.stringify(data),
|
||||
...options,
|
||||
});
|
||||
return handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a PUT request
|
||||
* @param {string} url - API endpoint
|
||||
* @param {object} data - Request body
|
||||
* @param {object} options - Fetch options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function put(url, data, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "PUT",
|
||||
headers: { ...DEFAULT_HEADERS, ...options.headers },
|
||||
body: JSON.stringify(data),
|
||||
...options,
|
||||
});
|
||||
return handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a DELETE request
|
||||
* @param {string} url - API endpoint
|
||||
* @param {object} options - Fetch options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function del(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "DELETE",
|
||||
headers: { ...DEFAULT_HEADERS, ...options.headers },
|
||||
...options,
|
||||
});
|
||||
return handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle API response
|
||||
* @param {Response} response - Fetch response
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function handleResponse(response) {
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const error = new Error(data.error || "An error occurred");
|
||||
error.status = response.status;
|
||||
error.data = data;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export default { get, post, put, del };
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue