Created
April 20, 2025 14:07
-
-
Save TLTechbender/03259b469f88f5a9da7977026274a75c to your computer and use it in GitHub Desktop.
Sample fetch wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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