Skip to content

Instantly share code, notes, and snippets.

@jscodelover
Last active April 6, 2023 17:39
Show Gist options
  • Save jscodelover/9ddae39b8a0681aa42eee9825d2e8268 to your computer and use it in GitHub Desktop.
Save jscodelover/9ddae39b8a0681aa42eee9825d2e8268 to your computer and use it in GitHub Desktop.
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()
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