Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TLTechbender/03259b469f88f5a9da7977026274a75c to your computer and use it in GitHub Desktop.
Save TLTechbender/03259b469f88f5a9da7977026274a75c to your computer and use it in GitHub Desktop.
Sample fetch wrapper
export default async function client(endpoint: string, { body, customConfig = {} }: { body?: any, customConfig?: RequestInit } = {}): Promise<void> {
const API_URL = "import.meta.env.API_URL"
const headers = { 'content-type': 'application/json' };
const config= {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
body: body ? JSON.stringify(body) : undefined,
};
try {
const response = await fetch(`${BASE_API_URL}${endpoint}`, config);
if (response.ok) {
return await response.json();
} else {
const errorData = await response.json();
const error = new Error();
error.message = errorData.message || 'API request failed';
error.name = `HTTP Error ${response.status}`;
(error as any).status = response.status;
(error as any).data = errorData;
throw error;
}
} catch (error) {
throw error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment