async function getAccessToken() { return ''; } export async function authenticatedFetch(...args: Parameters): Promise { const accessToken = await getAccessToken(); const body = args[1]?.body; const headers: RequestInit['headers'] & { 'Content-Type'?: string } = { ...(accessToken ? { authorization: `Bearer ${accessToken}` } : {}), ...args[1]?.headers, }; // Automatically set content type to application/json if body is FormData if (body instanceof FormData) { delete headers['Content-Type']; } else { headers['Content-Type'] = 'application/json'; } const response = await fetch(args[0], { ...args[1], mode: 'cors', cache: 'no-cache', headers, }); return (await response.json()) as T; } export async function get(url: string, query: object = {}, options: RequestInit = {}) { let resolvedUrl = url; if (Object.keys(query).length > 0) { resolvedUrl = `${resolvedUrl}?${new URLSearchParams( query as Record, ).toString()}`; } return await authenticatedFetch(resolvedUrl, { ...options, method: 'GET' }); } export async function post(url: string, body: object = {}, options: RequestInit = {}) { return await authenticatedFetch(url, { ...options, method: 'POST', body: JSON.stringify(body), }); } export async function postWithFiles( url: string, body: Record = {}, files: File[] = [], options: RequestInit = {}, ) { const formData = new FormData(); for (const key in body) { formData.append(key, body[key] as string); } for (const file of files) { formData.append('files', file); } return await authenticatedFetch(url, { ...options, method: 'POST', body: formData, }); } export async function put(url: string, body: object = {}, options: RequestInit = {}) { return await authenticatedFetch(url, { ...options, method: 'PUT', body: JSON.stringify(body), }); } export async function patch(url: string, body: object = {}, options: RequestInit = {}) { return await authenticatedFetch(url, { ...options, method: 'PATCH', body: JSON.stringify(body), }); } export async function del(url: string, body: object = {}, options: RequestInit = {}) { return await authenticatedFetch(url, { ...options, method: 'DELETE', body: JSON.stringify(body), }); }