Last active
May 22, 2022 08:14
-
-
Save MahdiTa97/4d86b1ca5495de3445fa34d53060230a to your computer and use it in GitHub Desktop.
Custom Fetch TypeScript Base
This file contains 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
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