2023-06-10 09:24:56 +00:00
|
|
|
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
|
2023-05-29 05:22:36 +00:00
|
|
|
|
2023-06-11 08:50:46 +00:00
|
|
|
export type FetchOptions = {
|
2023-06-10 09:24:56 +00:00
|
|
|
method: HttpMethod
|
|
|
|
headers?: Record<string, string>
|
|
|
|
body?: BodyInit
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetchRequest = async <T>(
|
2023-05-29 05:22:36 +00:00
|
|
|
url: string,
|
2023-06-10 09:24:56 +00:00
|
|
|
options: FetchOptions
|
|
|
|
): Promise<T> => {
|
|
|
|
try {
|
2023-06-14 11:09:55 +00:00
|
|
|
const baseUrl = import.meta.env.VITE_API_BASE_URL
|
|
|
|
const fullUrl = `${baseUrl}${url}`
|
|
|
|
|
|
|
|
const response = await fetch(fullUrl, options)
|
2023-06-10 09:24:56 +00:00
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
throw new Error('Request Error!')
|
|
|
|
}
|
|
|
|
|
|
|
|
const data: T = await response.json()
|
|
|
|
return data
|
|
|
|
} catch (error) {
|
|
|
|
throw new Error('Request Error!')
|
|
|
|
}
|
2023-05-29 05:22:36 +00:00
|
|
|
}
|
2023-06-10 09:24:56 +00:00
|
|
|
|
|
|
|
const fetchGet = async <T>(
|
|
|
|
url: string,
|
|
|
|
headers?: Record<string, string>
|
|
|
|
): Promise<T> => {
|
|
|
|
const options: FetchOptions = {
|
|
|
|
method: 'GET',
|
|
|
|
headers: headers,
|
|
|
|
}
|
|
|
|
|
|
|
|
return await fetchRequest<T>(url, options)
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetchPost = async <T>(
|
|
|
|
url: string,
|
|
|
|
body?: Record<string, any>,
|
|
|
|
headers?: Record<string, string>
|
|
|
|
): Promise<T> => {
|
|
|
|
const options: FetchOptions = {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
...headers,
|
|
|
|
},
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
}
|
|
|
|
|
|
|
|
return await fetchRequest<T>(url, options)
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetchPut = async <T>(
|
|
|
|
url: string,
|
|
|
|
body?: Record<string, any>,
|
|
|
|
headers?: Record<string, string>
|
|
|
|
): Promise<T> => {
|
|
|
|
const options: FetchOptions = {
|
|
|
|
method: 'PUT',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
...headers,
|
|
|
|
},
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
}
|
|
|
|
|
|
|
|
return await fetchRequest<T>(url, options)
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetchDelete = async <T>(
|
|
|
|
url: string,
|
|
|
|
headers?: Record<string, string>
|
|
|
|
): Promise<T> => {
|
|
|
|
const options: FetchOptions = {
|
|
|
|
method: 'DELETE',
|
|
|
|
headers: headers,
|
|
|
|
}
|
|
|
|
|
|
|
|
return await fetchRequest<T>(url, options)
|
|
|
|
}
|
|
|
|
|
|
|
|
export { fetchGet, fetchPost, fetchPut, fetchDelete }
|