Last active
April 6, 2023 17:39
-
-
Save jscodelover/9ddae39b8a0681aa42eee9825d2e8268 to your computer and use it in GitHub Desktop.
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 { myFetch } from './myFetch.js'; | |
async function withSuccess() { | |
const res = await myFetch({ url: 'https://dummyjson.com/todos' }) | |
if (res.message === 'Success') { | |
console.log('Yieee') | |
} else { | |
console.log(res.reason) | |
} | |
} | |
async function withFailure() { | |
const res = await myFetch({ url: 'https://dummyjson.com/toos' }) | |
if (res.message === 'Success') { | |
console.log('Yieee') | |
} else { | |
console.log(res.reason) | |
} | |
} | |
withSuccess(); | |
withFailure() |
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
function fetchRequestInterceptor(config) { | |
const { url, ...options } = config; | |
if (!options.method) { | |
options.method = 'GET' | |
} | |
console.log('We can add token or append base url here before sending the request') | |
return [url, options] | |
} | |
async function fetchResponsInterceptor(response) { | |
console.log('We can format the response here before sending the data back') | |
if (response.status === 200) { | |
const data = await response.json(); | |
return { message: 'Success', data } | |
} | |
return { message: 'Failed', data: null, reason: response.statusText } | |
} | |
async function myFetch(config) { | |
try { | |
const [url, options] = fetchRequestInterceptor(config); | |
const response = await fetch(url, options); | |
const data = await fetchResponsInterceptor(response); | |
return data | |
} | |
catch (err) { | |
console.warn('Something went wrong !!', err) | |
return { message: 'Failed', data: null, reason: err } | |
} | |
} | |
export { myFetch } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment