A tiny wrapper built around fetch with an intuitive syntax.
MIT License
Bot releases are hidden (Show)
export const apiClient = wretch('https://localhost:3000')
.addon(QueryStringAddon)
.resolve((chain) => {
return chain.unauthorized((_error, request) => {
// request type used to be wrong (missing .query() from the addon)
// and it would clash with what was expected by the callback definition
// now the type should be correct β¨
return request
.fetch()
.unauthorized((error) => {
throw error;
})
.json();
});
});
Published by elbywan 10 months ago
const fetcher = wretch("https://jsonplaceholder.typicode.com").addon({
// resolver can now be a function and to re-use the previously defined methods of the response chain:
resolver: (chain) => ['res', 'json', 'text', 'blob', 'formData', 'arrayBuffer'].reduce((acc, method) => ({
...acc,
// overrides .json, .text⦠methods to chain .then & .catch
[method](cb) {
return chain[method](cb)
.then(ret => (console.log('[hook] ok')))
.catch(error => {
console.error('[hook] error', error.response.url, error.response.status)
throw error
});
}
}), {})
});
(async function () {
await fetcher.get("/todos/1").json(console.log);
console.log("-----");
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
// [hook] ok
// -----
await fetcher.get("/bad-route").notFound(error => {
console.log('handled error :)')
}).text(console.log);
console.log("-----");
// handled error :)
// [hook] ok
// -----
await fetcher.get("/bad-route").text(console.log).catch(() => console.log('unhandled error :('));
// [hook] error https://jsonplaceholder.typicode.com/bad-route 404
// unhandled error :(
})()
Published by elbywan 11 months ago
const headers1 = new Headers({ "hello": "world" });
const headers2 = new Headers({ "bonjour": "le monde" });
const headers3 = { "hola": "mundo " };
const headers4 = [["hallo", "welt"]]
let w = wretch().headers(headers1);
console.log(w._options.headers);
// Object { hello: "world" }
w = w.headers(headers2);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde" }
w = w.headers(headers3);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde", hola: "mundo " }
w = w.headers(headers4);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde", hola: "mundo ", hallo: "welt" }
Published by elbywan about 1 year ago
<head>
<script type="module">
import wretch from 'https://cdn.skypack.dev/wretch';
import FormDataAddon from 'https://cdn.skypack.dev/wretch/addons/formData';
const fileInput = document.querySelector("#myfiles");
fileInput.addEventListener("change", () => {
wretch("/post-files")
.addon(FormDataAddon)
.formData({ files: fileInput.files })
.post()
.text(console.log)
});
</script>
</head>
<body>
<input id="myfiles" multiple type="file" />
</body>
Published by elbywan over 1 year ago
wretch(url)
.catcher(404, err => redirect("/routes/notfound", err.message))
.catcher(500, err => flashMessage("internal.server.error"))
// this fallback will trigger for any error except if already caught by other means (like above for 404s and 505s)
.catcherFallback(err => {
log("Uncaught error:", err)
throw err
})
Published by elbywan over 1 year ago
Published by elbywan over 1 year ago
Setting the error type as json manually using .errorType("json")
should now not be necessary if the server responds with a Content-Type
header set as application/json
.
The response body will be deserialized and the error.json
will be set accordingly.
Published by elbywan almost 2 years ago
Allows defining global error catchers using resolvers:
const request = wretch(baseURL)
.errorType("json")
.resolve((response) => {
return (
response
.error("Error", (error) => {
console.log("global catch (Error class)");
})
.error("TypeError", (error) => {
console.log("global type error catch (TypeError class)");
})
);
});
await request
.get(`/carts/v3/${cartId}/payment/modes`)
// Will override the global catcher now thanks to this fix.
.notFound((error) => {
console.log("not found");
})
.json();
Published by elbywan almost 2 years ago
Wretch now accepts a callback to monitor download progress.
import ProgressAddon from "wretch/addons/progress"
wretch("some_url")
// Register the addon
.addon(ProgressAddon())
.get()
// Log the progress as a percentage of completion
.progress((loaded, total) => console.log(`${(loaded / total * 100).toFixed(0)}%`))