Skip to content

Instantly share code, notes, and snippets.

@jonmircha
Last active May 9, 2024 16:03
Show Gist options
  • Save jonmircha/19a43c5714a398830d6834084f253a0a to your computer and use it in GitHub Desktop.
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
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,
};
};
@ChrisGlz14
Copy link

El mejor enseñando, no hay profe como el!

@Christopher-37
Copy link

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