test / src /lib /http.ts
aiioe's picture
Automated build & deploy
e454383 verified
Raw History Blame Contribute Delete
2.2 kB
// Import necessary types from TypeScript and fetch API
const port = 8000;
// const baseUrl = `https://obscure-spork-jr94576rpr53wgg-8000.app.github.dev/api/v1`;
// const baseUrl = `http://localhost:${port}/api/v1`;
const baseUrl = `/api/v1`;
// Define types for the request function parameters
type RequestMethod = "GET" | "POST" | "PUT" | "DELETE";
interface RequestHeaders {
[key: string]: string;
}
interface RequestOptions {
method: RequestMethod;
url: string;
data?: any; // Data can be of any type, though usually it's JSON or FormData
headers?: RequestHeaders;
bearerToken?: string | null;
}
// Utility function to handle requests
export async function request(
method: RequestMethod,
url: string,
data: any = null,
headers: RequestHeaders = {},
bearerToken: string | null = null
): Promise<Response> {
url = baseUrl + url;
// Define headers and options for the fetch API
let fetchOptions: RequestInit = {
method: method,
headers: {
"Content-Type": "application/json",
Authorization: bearerToken ? `Bearer ${bearerToken}` : "",
...headers,
},
};
// Adjust the Content-Type if data is FormData
if (data instanceof FormData) {
delete (fetchOptions.headers as Record<string, string>)["Content-Type"];
}
// Set request body if data is present
if (data !== null) {
fetchOptions.body = data instanceof FormData ? data : JSON.stringify(data);
}
// Send the request and return the fetch response
return fetch(url, fetchOptions);
}
// Define individual HTTP method functions
export function get(
url: string,
headers?: RequestHeaders,
bearerToken?: string
) {
return request("GET", url, null, headers, bearerToken);
}
export function post(
url: string,
data: any,
headers?: RequestHeaders,
bearerToken?: string
) {
return request("POST", url, data, headers, bearerToken);
}
export function put(
url: string,
data: any,
headers?: RequestHeaders,
bearerToken?: string
) {
return request("PUT", url, data, headers, bearerToken);
}
export function del(
url: string,
headers?: RequestHeaders,
bearerToken?: string
) {
return request("DELETE", url, null, headers, bearerToken);
}