first
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
function getHeaders(): Record<string, string> {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
}
|
||||
|
||||
async function get<T>(uri: string, baseUrl: string = ''): Promise<T> {
|
||||
const headers = getHeaders();
|
||||
const theUrl = baseUrl ? `${baseUrl}/${uri.replace(/^\//, '')}` : uri;
|
||||
const res = await fetch(theUrl, { headers });
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
async function post<T>(uri: string, payload?: unknown, baseUrl: string = ''): Promise<T> {
|
||||
const headers = getHeaders();
|
||||
const theUrl = baseUrl ? `${baseUrl}/${uri.replace(/^\//, '')}` : uri;
|
||||
const res = await fetch(theUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
headers,
|
||||
});
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
interface HttpClient {
|
||||
baseUrl: string;
|
||||
get: <T>(url: string) => Promise<T>;
|
||||
post: <T>(url: string, payload?: unknown) => Promise<T>;
|
||||
}
|
||||
|
||||
export function createClient(baseUrl?: string): HttpClient {
|
||||
const finalBaseUrl = baseUrl || '';
|
||||
return {
|
||||
baseUrl: finalBaseUrl,
|
||||
get: <T>(url: string) => get<T>(url, finalBaseUrl),
|
||||
post: <T>(url: string, payload?: unknown) => post<T>(url, payload, finalBaseUrl),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user