Last active
July 15, 2024 22:58
-
-
Save jonmircha/19a43c5714a398830d6834084f253a0a 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 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, | |
}; | |
}; |
gracias
Muchas Gracias!!!
thank you!
Muchas gracias Jon, sos un grande!
Mucha gracias!
El mejor enseñando, no hay profe como el!
Gracias por siempre compartir tus grandes conocimientos con el mundo :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gracias Profe!!!