wretch
is a small wrapper around fetch designed to simplify the way to perform network requests and handle responses.Fetch needs a second callback to process the response body.
fetch("examples/example.json") .then(response => response.json()) .then(json => { //Do stuff with the parsed json });
Wretch does it for you.
// Use .res for the raw response, .text for raw text, .json for json, .blob for a blob ... wretch("examples/example.json") .get() .json(json => { // Do stuff with the parsed json });
Fetch won’t reject on HTTP error status.
fetch("anything") .then(response => { if(!response.ok) { if(response.status === 404) throw new Error("Not found") else if(response.status === 401) throw new Error("Unauthorized") else if(response.status === 418) throw new Error("I'm a teapot !") else throw new Error("Other error") } else // ... }) .then(data => /* ... */) .catch(error => { /* ... */ })
Wretch throws when the response is not successful and contains helper methods to handle common codes.
wretch("anything") .get() .notFound(error => { /* ... */ }) .unauthorized(error => { /* ... */ }) .error(418, error => { /* ... */ }) .res(response => /* ... */) .catch(error => { /* uncaught errors */ })
With fetch you have to set the header, the method and the body manually.
fetch("endpoint", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ "hello": "world" }) }).then(response => /* ... */) // Omitting the data retrieval and error management parts…
With wretch, you have shorthands at your disposal.
wretch("endpoint") .post({ "hello": "world" }) .res(response => /* ... */)
A Wretch object is immutable which means that you can reuse previous instances safely.
// Cross origin authenticated requests on an external API const externalApi = wretch("http://external.api") // Base url // Authorization header .auth(`Bearer ${token}`) // Cors fetch options .options({ credentials: "include", mode: "cors" }) // Handle 403 errors .resolve((_) => _.forbidden(handle403)); // Fetch a resource const resource = await externalApi // Add a custom header for this request .headers({ "If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT" }) .get("/resource/1") .json(handleResource); // Post a resource externalApi .url("/resource") .post({ "Shiny new": "resource object" }) .json(handleNewResourceResult);
npm i wretch # or yarn/pnpm add wretch
The package contains multiple bundles depending on the format and feature set located under the /dist/bundle
folder.
💡 If you pick the core bundle, then to plug addons you must import them separately from
/dist/bundle/addons/[addonName].min.js
Feature set | File Name |
---|---|
Core features only | wretch.min.js |
Core + all addons | wretch.all.min.js |
Format | Extension |
---|---|
ESM | .min.mjs |
CommonJS | .min.cjs |
UMD | .min.js |
<!-- Pick your favourite CDN: - https://unpkg.com/wretch - https://cdn.jsdelivr.net/npm/wretch/ - https://www.skypack.dev/view/wretch - https://cdnjs.com/libraries/wretch - … --> <!-- UMD import as window.wretch --> <script src="https://unpkg.com/wretch"></script> <!-- Modern import --> <script type="module"> import wretch from 'https://cdn.skypack.dev/wretch/dist/bundle/wretch.all.min.mjs' // ... // </script>
wretch@^2
is compatible with modern browsers only. For older browsers please use wretch@^1
.
Wretch is compatible with and tested in Node.js >= 14. Older versions of node may work but it is not guaranteed.
Starting from Node.js 18, node includes experimental fetch support. Wretch will work without installing any polyfill.
For older versions, the Node.js standard library does not provide a native implementation of fetch (and other Browsers-only APIs) and polyfilling is mandatory.
The non-global way (preferred):
import fetch, { FormData } from "node-fetch" // w is a reusable wretch instance const w = wretch().polyfills({ fetch, FormData, });
Globally:
import fetch, { FormData } from "node-fetch"; // Either mutate the global object… global.fetch = fetch; global.FormData = FormData; // …or use the static wretch.polyfills method to impact every wretch instance created afterwards. wretch.polyfills({ fetch, FormData, });
Works with Deno >= 0.41.0 out of the box.
Types should be imported from /dist/types.d.ts
.
// You can import wretch from any CDN that serve ESModules. import wretch from "https://cdn.skypack.dev/wretch"; const text = await wretch("https://httpstat.us").get("/200").text(); console.log(text); // -> 200 OK
// ECMAScript modules import wretch from "wretch" // CommonJS const wretch = require("wretch") // Global variable (script tag) window.wretch
import wretch from "wretch" // Instantiate and configure wretch const api = wretch("https://jsonplaceholder.typicode.com", { mode: "cors" }) .errorType("json") .resolve(r => r.json()) try { // Fetch users const users = await api.get("/users") // Find all posts from a given user const user = users.find(({ name }) => name === "Nicholas Runolfsdottir V") const postsByUser = await api.get(`/posts?userId=${user.id}`) // Create a new post const newPost = await api.url("/posts").post({ title: "New Post", body: "My shiny new post" }) // Patch it await api.url("/posts/" + newPost.id).patch({ title: "Updated Post", body: "Edited body" }) // Fetch it await api.get("/posts/" + newPost.id) } catch (error) { // The API could return an empty object - in which case the status text is logged instead. const message = typeof error.message === "object" && Object.keys(error.message).length > 0 ? JSON.stringify(error.message) : error.response.statusText console.error(`${error.status}: ${message}`) }
A high level overview of the successive steps that can be chained to perform a request and parse the result.
// First, instantiate wretch wretch(baseUrl, baseOptions)
The "request" chain starts here.
// Optional - A set of helper methods to set the default options, set accept header, change the current url… .<helper method(s)>() // Optional - Serialize an object to json or FormData formats and sets the body & header field if needed .<body type>() // Required - Sends the get/put/post/delete/patch request. .<http method>()
The "response" chain starts here.
Fetch is called after the request chain ends and before the response chain starts.<br> The request is on the fly and now it is time to chain catchers and finally call a response type handler.
// Optional - You can chain error handlers here .<catcher(s)>() // Required - Specify the data type you need, which will be parsed and handed to you .<response type>() // >> Ends the response chain.
From this point on, wretch returns a standard Promise.
.then(…) .catch(…)
💡 The API documentation is now autogenerated and hosted separately, click the links access it.
These methods are available from the main default export and can be used to instantiate wretch and configure it globally.
import wretch from "wretch" wretch.options({ mode: "cors" }) let w = wretch("http://domain.com/", { cache: "default" })
Helper Methods are used to configure the request and program actions.
w = w .url("/resource/1") .headers({ "Cache-Control": no-cache }) .content("text/html")
Specify a body type if uploading data. Can also be added through the HTTP Method argument.
w = w.body("<html><body><div/></body></html>")
Sets the HTTP method and sends the request.
Calling an HTTP method ends the request chain and returns a response chain. You can pass optional url and body arguments to these methods.
// These shorthands: wretch().get("/url"); wretch().post({ json: "body" }, "/url"); // Are equivalent to: wretch().url("/url").get(); wretch().json({ json: "body" }).url("/url").post();
NOTE: if the body argument is an Object
it is assumed that it is a JSON payload and it will have the same behaviour as calling .json(body)
unless the Content-Type
header has been set to something else beforehand.
Catchers are optional, but if none are provided an error will still be thrown for http error codes and it will be up to you to catch it.
wretch("...") .get() .badRequest((err) => console.log(err.status)) .unauthorized((err) => console.log(err.status)) .forbidden((err) => console.log(err.status)) .notFound((err) => console.log(err.status)) .timeout((err) => console.log(err.status)) .internalError((err) => console.log(err.status)) .error(418, (err) => console.log(err.status)) .fetchError((err) => console.log(err)) .res();
The error passed to catchers is enhanced with additional properties.
type WretchError = Error & { status: number; response: WretchResponse; text?: string; json?: Object; };
The original request is passed along the error and can be used in order to perform an additional request.
wretch("/resource") .get() .unauthorized(async (error, req) => { // Renew credentials const token = await wretch("/renewtoken").get().text(); storeToken(token); // Replay the original request with new credentials return req.auth(token).get().unauthorized((err) => { throw err; }).json(); }) .json() // The promise chain is preserved as expected // ".then" will be performed on the result of the original request // or the replayed one (if a 401 error was thrown) .then(callback);
Setting the final response body type ends the chain and returns a regular promise.
All these methods accept an optional callback, and will return a Promise resolved with either the return value of the provided callback or the expected type.
// Without a callback wretch("...").get().json().then(json => /* json is the parsed json of the response body */) // Without a callback using await const json = await wretch("...").get().json() // With a callback the value returned is passed to the Promise wretch("...").get().json(json => "Hello world!").then(console.log) // => Hello world!
If an error is caught by catchers, the response type handler will not be called.
Addons are separate pieces of code that you can import and plug into wretch
to add new features.
import FormDataAddon from "wretch/addons/formData" import QueryStringAddon from "wretch/addons/queryString" // Add both addons const w = wretch().addon(FormDataAddon).addon(QueryStringAddon) // Additional features are now available w.formData({ hello: "world" }).query({ check: true })
Typescript should also be fully supported and will provide
最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。
像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写 、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工 具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内 容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号