-
-
Save kralion/5dfbef659b77ddad1a00b9c291c12d2f to your computer and use it in GitHub Desktop.
Script que te permite simplificar peticiones HTTP con Fetch, esta escrita en VanillaJS por lo que puedes usarla con cualquier framework o librería
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
export const helpHttp = () => { | |
const customFetch = (endpoint, options) => { | |
const defaultHeader = { | |
accept: "application/json", | |
}; | |
const controller = new AbortController(); | |
options.signal = controller.signal; | |
options.method = options.method || "GET"; | |
options.headers = options.headers | |
? { ...defaultHeader, ...options.headers } | |
: defaultHeader; | |
options.body = JSON.stringify(options.body) || false; | |
if (!options.body) delete options.body; | |
//console.log(options); | |
setTimeout(() => controller.abort(), 3000); | |
return fetch(endpoint, options) | |
.then((res) => | |
res.ok | |
? res.json() | |
: Promise.reject({ | |
err: true, | |
status: res.status || "00", | |
statusText: res.statusText || "Ocurrió un error", | |
}) | |
) | |
.catch((err) => err); | |
}; | |
const get = (url, options = {}) => customFetch(url, options); | |
const post = (url, options = {}) => { | |
options.method = "POST"; | |
return customFetch(url, options); | |
}; | |
const put = (url, options = {}) => { | |
options.method = "PUT"; | |
return customFetch(url, options); | |
}; | |
const del = (url, options = {}) => { | |
options.method = "DELETE"; | |
return customFetch(url, options); | |
}; | |
return { | |
get, | |
post, | |
put, | |
del, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment