Files
platform/src/workspaces/injector/use-client.ts
T
2026-02-16 19:34:35 +00:00

39 lines
1.1 KiB
TypeScript

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),
};
}