Skip to content

Instantly share code, notes, and snippets.

@jonmircha
Last active January 29, 2025 04:11
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,
};
};
@joselo19
Copy link

Gracias MAESTRO!!

@mark-1701
Copy link

Pensé que mi helper http era bueno, pero ahora tengo uno mejor. Muchas gracias.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment