Skip to content

Instantly share code, notes, and snippets.

@MahdiTa97
Last active May 22, 2022 08:14
Show Gist options
  • Save MahdiTa97/4d86b1ca5495de3445fa34d53060230a to your computer and use it in GitHub Desktop.
Save MahdiTa97/4d86b1ca5495de3445fa34d53060230a to your computer and use it in GitHub Desktop.
Custom Fetch TypeScript Base
import { getStoredOptions, setStoredOptions } from '../work-with-api/storage';
const BASE_URL = 'https://test.com';
async function apiClient(
endpoint: string,
{ body, ...customConfig }: RequestInit = {}
) {
const res = await getStoredOptions();
const headers: HeadersInit = { 'content-type': 'application/json' };
if (res?.authToken) {
headers.Authorization = `Bearer ${res.authToken}`;
}
const config: RequestInit = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
};
if (body) {
config.body = JSON.stringify(body);
}
const response = await fetch(`${BASE_URL}/${endpoint}`, config);
if (response.status === 401) {
logout();
return;
}
if (response.ok) {
return await response.json();
} else {
const errorMessage = await response.text();
return Promise.reject(new Error(errorMessage));
}
}
function logout() {
setStoredOptions({
authToken: null,
isLoggedIn: false,
});
}
export default apiClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment