Last active
August 27, 2024 09:04
-
-
Save caub/2462e4af4f66114581907e8df9623590 to your computer and use it in GitHub Desktop.
Simple fetch wrapper example for your API calls
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
function fetchJson(path, {method, body}) { | |
return fetch(`${API_BASE_URL}${path}`, { | |
method, | |
// credentials: 'include', // Use either 1. this if using cookies-based authentication | |
headers: { | |
// either nothing (if using cookies (requires same domain) | |
// Authorization: `Bearer ${localStorage.getItem('access_token')}`, // or this (client-side) | |
// Authorization: `ApiKey ${process.env.SG_API_KEY}`, // or access token authentication (server-side) | |
...body && {'Content-Type': 'application/json'}, | |
}, | |
body: body && JSON.stringify(body) | |
}).then(async r => { | |
const data = await r.json().catch(() => ({})); | |
if (r.ok) return data; | |
const err = new Error(data?.error.message || data); | |
err.status = r.status; | |
throw err; | |
}); | |
} | |
export default new Proxy(fetchJson, { | |
get: (fn, method) => typeof method === 'string' ? (url, body) => fn(url, { method, body }) : fn | |
}); | |
// Usage: | |
// const items = await api.get('/v1/items'); | |
// await api.put('/v1/user', { language: 'es' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment