Wretch

A tiny wrapper built around fetch with an intuitive syntax.

README

wretch-logo

Wretch

github-badge npm-badge npm-downloads-badge Coverage Status license-badge

A tiny (~1.9KB g-zipped) wrapper built around fetch with an intuitive syntax.

f[ETCH] [WR]apper

Wretch 2.1 is now live 🎉 ! Please have a look at the releases and the changelog after each update for new features and breaking changes. If you want to try out the hot stuff, please look into the dev branch.

And if you like the library please consider becoming a sponsor ❤️.

Features


wretch is a small wrapper around fetch designed to simplify the way to perform network requests and handle responses.


- 🪶 Small - core is less than 2KB g-zipped
- 💡 Intuitive - lean API, handles errors, headers and (de)serialization
- 🧊 Immutable - every call creates a cloned instance that can then be reused safely
- 🔌 Modular - plug addons to add new features, and middlewares to intercept requests
- 🧩 Isomorphic - compatible with modern browsers, Node.js 14+ and Deno
- 🦺 Type safe - strongly typed, written in TypeScript
- ✅ Proven - fully covered by unit tests and widely used
- 💓 Maintained - alive and well for many years

Table of Contents


- [Motivation](#motivation)
- [Installation](#installation)
- [Compatibility](#compatibility)
- [Usage](#usage)
- [Api](#api-)
- [Addons](#addons)
- [Middlewares](#middlewares)
- [Migration from v1](#migration-from-v1)
- [License](#license)

Motivation


Because having to write a second callback to process a response body feels awkward.


Fetch needs a second callback to process the response body.

  1. ``` js
  2. fetch("examples/example.json")
  3.   .then(response => response.json())
  4.   .then(json => {
  5.     //Do stuff with the parsed json
  6.   });
  7. ```

Wretch does it for you.

  1. ``` js
  2. // Use .res for the raw response, .text for raw text, .json for json, .blob for a blob ...
  3. wretch("examples/example.json")
  4.   .get()
  5.   .json(json => {
  6.     // Do stuff with the parsed json
  7.   });
  8. ```

Because manually checking and throwing every request error code is tedious.


Fetch won’t reject on HTTP error status.

  1. ``` js
  2. fetch("anything")
  3.   .then(response => {
  4.     if(!response.ok) {
  5.       if(response.status === 404) throw new Error("Not found")
  6.       else if(response.status === 401) throw new Error("Unauthorized")
  7.       else if(response.status === 418) throw new Error("I'm a teapot !")
  8.       else throw new Error("Other error")
  9.     }
  10.     else // ...
  11.   })
  12.   .then(data => /* ... */)
  13.   .catch(error => { /* ... */ })
  14. ```

Wretch throws when the response is not successful and contains helper methods to handle common codes.

  1. ``` js
  2. wretch("anything")
  3.   .get()
  4.   .notFound(error => { /* ... */ })
  5.   .unauthorized(error => { /* ... */ })
  6.   .error(418, error => { /* ... */ })
  7.   .res(response => /* ... */)
  8.   .catch(error => { /* uncaught errors */ })
  9. ```

Because sending a json object should be easy.


With fetch you have to set the header, the method and the body manually.

  1. ``` js
  2. fetch("endpoint", {
  3.   method: "POST",
  4.   headers: { "Content-Type": "application/json" },
  5.   body: JSON.stringify({ "hello": "world" })
  6. }).then(response => /* ... */)
  7. // Omitting the data retrieval and error management parts…
  8. ```

With wretch, you have shorthands at your disposal.

  1. ``` js
  2. wretch("endpoint")
  3.   .post({ "hello": "world" })
  4.   .res(response => /* ... */)
  5. ```

Because configuration should not rhyme with repetition.


A Wretch object is immutable which means that you can reuse previous instances safely.

  1. ``` js
  2. // Cross origin authenticated requests on an external API
  3. const externalApi = wretch("http://external.api") // Base url
  4.   // Authorization header
  5.   .auth(`Bearer ${token}`)
  6.   // Cors fetch options
  7.   .options({ credentials: "include", mode: "cors" })
  8.   // Handle 403 errors
  9.   .resolve((_) => _.forbidden(handle403));

  10. // Fetch a resource
  11. const resource = await externalApi
  12.   // Add a custom header for this request
  13.   .headers({ "If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT" })
  14.   .get("/resource/1")
  15.   .json(handleResource);

  16. // Post a resource
  17. externalApi
  18.   .url("/resource")
  19.   .post({ "Shiny new": "resource object" })
  20.   .json(handleNewResourceResult);
  21. ```

Installation


Package Manager


  1. ```sh
  2. npm i wretch # or yarn/pnpm add wretch
  3. ```

<script> tag


The package contains multiple bundles depending on the format and feature set located under the /dist/bundle folder.

Bundle variants

💡 If you pick the core bundle, then to plug addons you must import them separately from /dist/bundle/addons/[addonName].min.js


FeatureFile
-------------------------------------
Core`wretch.min.js`
Core`wretch.all.min.js`

FormatExtension
------------------
ESM`.min.mjs`
CommonJS`.min.cjs`
UMD`.min.js`


  1. ``` html
  2. <!--
  3.   Pick your favourite CDN:
  4.     - https://unpkg.com/wretch
  5.     - https://cdn.jsdelivr.net/npm/wretch/
  6.     - https://www.skypack.dev/view/wretch
  7.     - https://cdnjs.com/libraries/wretch
  8.     - …
  9. -->
  10. <script src="https://unpkg.com/wretch"></script>
  11. <script type="module">
  12.   import wretch from 'https://cdn.skypack.dev/wretch/dist/bundle/wretch.all.min.mjs'
  13.   // ... //
  14. </script>
  15. ```

Compatibility


Browsers


wretch@^2 is compatible with modern browsers only. For older browsers please use wretch@^1.

Node.js


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 of Node.js, Wretch requires installing FormData and fetch polyfills.


Polyfills


Since the Node.js standard library does not provide a native implementation of fetch (and other Browsers-only APIs), polyfilling is mandatory.

_The non-global way (preferred):_

  1. ``` js
  2. // w is a reusable wretch instance
  3. const w = wretch().polyfills({
  4.   fetch: require("node-fetch"),
  5.   FormData: require("form-data"),
  6.   URLSearchParams: require("url").URLSearchParams,
  7. });
  8. ```

_Globally:_

  1. ``` js
  2. // Either mutate the global object…
  3. global.fetch = require("node-fetch");
  4. global.FormData = require("form-data");
  5. global.URLSearchParams = require("url").URLSearchParams;

  6. // …or use the static wretch.polyfills method to impact every wretch instance created afterwards.
  7. wretch.polyfills({
  8.   fetch: require("node-fetch"),
  9.   FormData: require("form-data"),
  10.   URLSearchParams: require("url").URLSearchParams,
  11. });
  12. ```

Deno


Works with Deno >=
0.41.0 out of the box.

Types should be imported from /dist/types.d.ts.

  1. ```ts
  2. // You can import wretch from any CDN that serve ESModules.
  3. import wretch from "https://cdn.skypack.dev/wretch";

  4. const text = await wretch("https://httpstat.us").get("/200").text();
  5. console.log(text); // -> 200 OK
  6. ```

Usage


Import


  1. ```typescript
  2. // ECMAScript modules
  3. import wretch from "wretch"
  4. // CommonJS
  5. const wretch = require("wretch")
  6. // Global variable (script tag)
  7. window.wretch
  8. ```

Minimal Example


  1. ``` js
  2. import wretch from "wretch"

  3. // Instantiate and configure wretch
  4. const api =
  5.   wretch("https://jsonplaceholder.typicode.com", { mode: "cors" })
  6.     .errorType("json")
  7.     .resolve(r => r.json())

  8. try {
  9.   // Fetch users
  10.   const users = await api.get("/users")
  11.   // Find all posts from a given user
  12.   const user = users.find(({ name }) => name === "Nicholas Runolfsdottir V")
  13.   const postsByUser = await api.get(`/posts?userId=${user.id}`)
  14.   // Create a new post
  15.   const newPost = await api.url("/posts").post({
  16.     title: "New Post",
  17.     body: "My shiny new post"
  18.   })
  19.   // Patch it
  20.   await api.url("/posts/" + newPost.id).patch({
  21.     title: "Updated Post",
  22.     body: "Edited body"
  23.   })
  24.   // Fetch it
  25.   await api.get("/posts/" + newPost.id)
  26. } catch (error) {
  27.   // The API could return an empty object - in which case the status text is logged instead.
  28.   const message =
  29.     typeof error.message === "object" && Object.keys(error.message).length > 0
  30.       ? JSON.stringify(error.message)
  31.       : error.response.statusText
  32.   console.error(`${error.status}: ${message}`)
  33. }
  34. ```

Chaining


A high level overview of the successive steps that can be chained to perform a request and parse the result.

  1. ```ts
  2. // First, instantiate wretch
  3. wretch(baseUrl, baseOptions)
  4. ```

_The "request" chain starts here._

  1. ```ts
  2.   // Optional - A set of helper methods to set the default options, set accept header, change the current url…
  3.   .<helper method(s)>()
  4.   // Optional - Serialize an object to json or FormData formats and sets the body & header field if needed
  5.   .<body type>()
  6.     // Required - Sends the get/put/post/delete/patch request.
  7.   .<http method>()
  8. ```

_The "response" chain starts here._

_Fetch is called after the request chain ends and before the response chain starts._
_The request is on the fly and now it is time to chain catchers and finally call a response type handler._

  1. ```ts
  2.   // Optional - You can chain error handlers here
  3.   .<catcher(s)>()
  4.   // Required - Specify the data type you need, which will be parsed and handed to you
  5.   .<response type>()
  6.   // >> Ends the response chain.
  7. ```

_From this point on, wretch returns a standard Promise._

  1. ```ts
  2.   .then()
  3.   .catch()
  4. ```


💡 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.

  1. ``` js
  2. import wretch from "wretch"

  3. wretch.options({ mode: "cors" })

  4. let w = wretch("http://domain.com/", { cache: "default" })
  5. ```


Helper Methods are used to configure the request and program actions.

  1. ``` js
  2. w = w
  3.   .url("/resource/1")
  4.   .headers({ "Cache-Control": no-cache })
  5.   .content("text/html")
  6. ```


Specify a body type if uploading data. Can also be added through the HTTP Method argument.

  1. ``` js
  2. w = w.body("<html><body><div/></body></html>")
  3. ```


Setus 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.

  1. ``` js
  2. // These shorthands:
  3. wretch().get("/url");
  4. wretch().post({ json: "body" }, "/url");
  5. // Are equivalent to:
  6. wretch().url("/url").get();
  7. wretch().json({ json: "body" }).url("/url").post();
  8. ```

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.

  1. ``` js
  2. wretch("...")
  3.   .get()
  4.   .badRequest((err) => console.log(err.status))
  5.   .unauthorized((err) => console.log(err.status))
  6.   .forbidden((err) => console.log(err.status))
  7.   .notFound((err) => console.log(err.status))
  8.   .timeout((err) => console.log(err.status))
  9.   .internalError((err) => console.log(err.status))
  10.   .error(418, (err) => console.log(err.status))
  11.   .fetchError((err) => console.log(err))
  12.   .res();
  13. ```

The error passed to catchers is enhanced with additional properties.

  1. ```ts
  2. type WretchError = Error & {
  3.   status: number;
  4.   response: WretchResponse;
  5.   text?: string;
  6.   json?: Object;
  7. };
  8. ```

The original request is passed along the error and can be used in order to
perform an additional request.

  1. ``` js
  2. wretch("/resource")
  3.   .get()
  4.   .unauthorized(async (error, req) => {
  5.     // Renew credentials
  6.     const token = await wretch("/renewtoken").get().text();
  7.     storeToken(token);
  8.     // Replay the original request with new credentials
  9.     return req.auth(token).get().unauthorized((err) => {
  10.       throw err;
  11.     }).json();
  12.   })
  13.   .json()
  14.   // The promise chain is preserved as expected
  15.   // ".then" will be performed on the result of the original request
  16.   // or the replayed one (if a 401 error was thrown)
  17.   .then(callback);
  18. ```


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.

  1. ``` js
  2. // Without a callback
  3. wretch("...").get().json().then(json => /* json is the parsed json of the response body */)
  4. // Without a callback using await
  5. const json = await wretch("...").get().json()
  6. // With a callback the value returned is passed to the Promise
  7. wretch("...").get().json(json => "Hello world!").then(console.log) // => Hello world!
  8. ```

_If an error is caught by catchers, the response type handler will not be
called._

Addons


Addons are separate pieces of code that you can import and plug into wretch to add new features.

  1. ``` js
  2. import FormDataAddon from "wretch/addons/formData"
  3. import QueryStringAddon from "wretch/addons/queryString"

  4. // Add both addons
  5. const w = wretch().addon(FormDataAddon).addon(QueryStringAddon)

  6. // Additional features are now available
  7. w.formData({ hello: "world" }).query({ check: true })
  8. ```

Typescript should also be fully supported and will provide completions.

https://user-images.githubusercontent.com/3428394/182319457-504a0856-abdd-4c1d-bd04-df5a061e515d.mov


Used to construct and append the query string part of the URL from an object.

  1. ``` js
  2. import QueryStringAddon from "wretch/addons/queryString"
  3. ```


Adds a helper method to serialize a multipart/form-data body from an object.

  1. ``` js
  2. import FormDataAddon from "wretch/addons/formData"
  3. ```


Adds a method to serialize a application/x-www-form-urlencoded body from an object.

  1. ``` js
  2. import FormUrlAddon from "wretch/addons/formUrl"
  3. ```


Adds the ability to abort requests and set timeouts using AbortController and signals under the hood.

  1. ``` js
  2. import AbortAddon from "wretch/addons/abort"
  3. ```

_Only compatible with browsers that support
Otherwise, you could use a (partial)

Use cases :

  1. ``` js
  2. const [c, w] = wretch("...")
  3.   .addon(AbortAddon())
  4.   .get()
  5.   .onAbort((_) => console.log("Aborted !"))
  6.   .controller();

  7. w.text((_) => console.log("should never be called"));
  8. c.abort();

  9. // Or :

  10. const controller = new AbortController();

  11. wretch("...")
  12.   .addon(AbortAddon())
  13.   .signal(controller)
  14.   .get()
  15.   .onAbort((_) => console.log("Aborted !"))
  16.   .text((_) => console.log("should never be called"));

  17. controller.abort();
  18. ```

  1. ``` js
  2. // 1 second timeout
  3. wretch("...").addon(AbortAddon()).get().setTimeout(1000).json(_ =>
  4.   // will not be called if the request timeouts
  5. )
  6. ```


Adds the ability to measure requests using the Performance Timings API.

Uses the Performance API (browsers & Node.js) to expose timings related to the underlying request.

💡 Make sure to follow the additional instructions in the documentation to setup Node.js if necessary.


Middlewares


Middlewares are functions that can intercept requests before being processed by
Fetch. Wretch includes a helper to help replicate the
middleware style.

  1. ``` js
  2. import wretch from "wretch"
  3. import { retry, dedupe } from "wretch/middlewares"

  4. const w = wretch().middlewares([retry(), dedupe()])
  5. ```

💡 The following middlewares were previously provided by the [wretch-middlewares](https://github.com/elbywan/wretch-middlewares/) package.



Retries a request multiple times in case of an error (or until a custom condition is true).

  1. ``` js
  2. import wretch from 'wretch'
  3. import { retry } from 'wretch/middlewares'

  4. wretch().middlewares([
  5.   retry({
  6.     /* Options - defaults below */
  7.     delayTimer: 500,
  8.     delayRamp: (delay, nbOfAttempts) => delay * nbOfAttempts,
  9.     maxAttempts: 10,
  10.     until: (response, error) => response && response.ok,
  11.     onRetry: null,
  12.     retryOnNetworkError: false,
  13.     resolveWithLatestResponse: false
  14.   })
  15. ])./* ... */

  16. // You can also return a Promise, which is useful if you want to inspect the body:
  17. wretch().middlewares([
  18.   retry({
  19.     until: response =>
  20.       response.clone().json().then(body =>
  21.         body.field === 'something'
  22.       )
  23.   })
  24. ])
  25. ```


Prevents having multiple identical requests on the fly at the same time.

  1. ``` js
  2. import wretch from 'wretch'
  3. import { dedupe } from 'wretch/middlewares'

  4. wretch().middlewares([
  5.   dedupe({
  6.     /* Options - defaults below */
  7.     skip: (url, opts) => opts.skipDedupe || opts.method !== 'GET',
  8.     key: (url, opts) => opts.method + '@' + url,
  9.     resolver: response => response.clone()
  10.   })
  11. ])./* ... */
  12. ```


A throttling cache which stores and serves server responses for a certain amount of time.

  1. ``` js
  2. import wretch from 'wretch'
  3. import { throttlingCache } from 'wretch/middlewares'

  4. wretch().middlewares([
  5.   throttlingCache({
  6.     /* Options - defaults below */
  7.     throttle: 1000,
  8.     skip: (url, opts) => opts.skipCache || opts.method !== 'GET',
  9.     key: (url, opts) => opts.method + '@' + url,
  10.     clear: (url, opts) => false,
  11.     invalidate: (url, opts) => null,
  12.     condition: response => response.ok,
  13.     flagResponseOnCacheHit: '__cached'
  14.   })
  15. ])./* ... */
  16. ```


Delays the request by a specific amount of time.

  1. ``` js
  2. import wretch from 'wretch'
  3. import { delay } from 'wretch/middlewares'

  4. wretch().middlewares([
  5.   delay(1000)
  6. ])./* ... */
  7. ```

Writing a Middleware


Basically a Middleware is a function having the following signature :

  1. ```ts
  2. // A middleware accepts options and returns a configured version
  3. type Middleware = (options?: { [key: string]: any }) => ConfiguredMiddleware;
  4. // A configured middleware (with options curried)
  5. type ConfiguredMiddleware = (next: FetchLike) => FetchLike;
  6. // A "fetch like" function, accepting an url and fetch options and returning a response promise
  7. type FetchLike = (
  8.   url: string,
  9.   opts: WretchOptions,
  10. ) => Promise<WretchResponse>;
  11. ```

Context


If you need to manipulate data within your middleware and expose it for later
consumption, a solution could be to pass a named property to the wretch options
(_suggested name: context_).

Your middleware can then take advantage of that by mutating the object
reference.

  1. ``` js
  2. const contextMiddleware = (next) =>
  3.   (url, opts) => {
  4.     if (opts.context) {
  5.       // Mutate "context"
  6.       opts.context.property = "anything";
  7.     }
  8.     return next(url, opts);
  9.   };

  10. // Provide the reference to a "context" object
  11. const context = {};
  12. const res = await wretch("...")
  13.   // Pass "context" by reference as an option
  14.   .options({ context })
  15.   .middlewares([contextMiddleware])
  16.   .get()
  17.   .res();

  18. console.log(context.property); // prints "anything"
  19. ```

Advanced examples


 👀 Show me the code

  1. ``` js
  2. /* A simple delay middleware. */
  3. const delayMiddleware = delay => next => (url, opts) => {
  4.   return new Promise(res => setTimeout(() => res(next(url, opts)), delay))
  5. }

  6. /* Returns the url and method without performing an actual request. */
  7. const shortCircuitMiddleware = () => next => (url, opts) => {
  8.   // We create a new Response object to comply because wretch expects that from fetch.
  9.   const response = new Response()
  10.   response.text = () => Promise.resolve(opts.method + "@" + url)
  11.   response.json = () => Promise.resolve({ url, method: opts.method })
  12.   // Instead of calling next(), returning a Response Promise bypasses the rest of the chain.
  13.   return Promise.resolve(response)
  14. }

  15. /* Logs all requests passing through. */
  16. const logMiddleware = () => next => (url, opts) => {
  17.   console.log(opts.method + "@" + url)
  18.   return next(url, opts)
  19. }

  20. /* A throttling cache. */
  21. const cacheMiddleware = (throttle = 0) => {

  22.   const cache = new Map()
  23.   const inflight = new Map()
  24.   const throttling = new Set()

  25.   return next => (url, opts) => {
  26.     const key = opts.method + "@" + url

  27.     if(!opts.noCache && throttling.has(key)) {
  28.       // If the cache contains a previous response and we are throttling, serve it and bypass the chain.
  29.       if(cache.has(key))
  30.         return Promise.resolve(cache.get(key).clone())
  31.       // If the request in already in-flight, wait until it is resolved
  32.       else if(inflight.has(key)) {
  33.         return new Promise((resolve, reject) => {
  34.           inflight.get(key).push([resolve, reject])
  35.         })
  36.       }
  37.     }

  38.     // Init. the pending promises Map
  39.     if(!inflight.has(key))
  40.       inflight.set(key, [])

  41.     // If we are not throttling, activate the throttle for X milliseconds
  42.     if(throttle && !throttling.has(key)) {
  43.       throttling.add(key)
  44.       setTimeout(() => { throttling.delete(key) }, throttle)
  45.     }

  46.     // We call the next middleware in the chain.
  47.     return next(url, opts)
  48.       .then(_ => {
  49.         // Add a cloned response to the cache
  50.         cache.set(key, _.clone())
  51.         // Resolve pending promises
  52.         inflight.get(key).forEach((([resolve, reject]) => resolve(_.clone()))
  53.         // Remove the inflight pending promises
  54.         inflight.delete(key)
  55.         // Return the original response
  56.         return _
  57.       })
  58.       .catch(_ => {
  59.         // Reject pending promises on error
  60.         inflight.get(key).forEach(([resolve, reject]) => reject(_))
  61.         inflight.delete(key)
  62.         throw _
  63.       })
  64.   }
  65. }

  66. // To call a single middleware
  67. const cache = cacheMiddleware(1000)
  68. wretch("...").middlewares([cache]).get()

  69. // To chain middlewares
  70. wretch("...").middlewares([
  71.   logMiddleware(),
  72.   delayMiddleware(1000),
  73.   shortCircuitMiddleware()
  74. }).get().text(_ => console.log(text))

  75. // To test the cache middleware more thoroughly
  76. const wretchCache = wretch().middlewares([cacheMiddleware(1000)])
  77. const printResource = (url, timeout = 0) =>
  78.   setTimeout(_ => wretchCache.url(url).get().notFound(console.error).text(console.log), timeout)
  79. // The resource url, change it to an invalid route to check the error handling
  80. const resourceUrl = "/"
  81. // Only two actual requests are made here even though there are 30 calls
  82. for(let i = 0; i < 10; i++) {
  83.   printResource(resourceUrl)
  84.   printResource(resourceUrl, 500)
  85.   printResource(resourceUrl, 1500)
  86. }
  87. ```


Migration from v1


Philosophy


Wretch has been completely rewritten with the following goals in mind:

- reduce its size by making it modular
- preserve the typescript type coverage
- improve the API by removing several awkward choices

Compatibility


wretch@1 was transpiled to es5, wretch@2 is now transpiled to es2018.
Any "modern" browser and Node.js versions >= 14 should parse the library without issues.

If you need compatibility with older browsers/nodejs versions then either stick with v1, use poyfills
or configure @babel to make it transpile wretch.

Addons


Some features that were part of wretch v1 are now split apart and must be imported through addons.
It is now needed to pass the Addon to the [.addon](#addonaddon-wretchaddon) method to register it.

Please refer to the Addons documentation.

  1. ``` js
  2. /* Previously (wretch@1) */
  3. import wretch from "wretch"

  4. wretch.formData({ hello: "world" }).query({ check: true })

  5. /* Now (wretch@2) */
  6. import FormDataAddon from "wretch/addons/formData"
  7. import QueryStringAddon from "wretch/addons/queryString"
  8. import wretch as baseWretch from "wretch"

  9. // Add both addons
  10. const wretch = baseWretch().addon(FormDataAddon).addon(QueryStringAddon)

  11. // Additional features are now available
  12. wretch.formData({ hello: "world" }).query({ check: true })
  13. ```

Typescript


Types have been renamed and refactored, please update your imports accordingly and refer to the typescript api documentation.

API Changes


Replace / Mixin arguments


Some functions used to have a mixin = true argument that could be used to merge the value, others a replace = false argument performing the opposite.
In v2 there are only replace = false arguments but the default behaviour should be preserved.

  1. ``` js
  2. /* Previously (wretch@1) */
  3. wretch.options({ credentials: "same-origin" }, false) // false: do not merge the value
  4. wretch.options({ credentials: "same-origin" }) // Default behaviour stays the same

  5. /* Now (wretch@2) */
  6. wretch.options({ credentials: "same-origin" }, true) // true: replace the existing value
  7. wretch.options({ credentials: "same-origin" }) // Default behaviour stays the same
  8. ```

HTTP methods extra argument


In v1 it was possible to set fetch options while calling the http methods to end the request chain.

  1. ``` js
  2. /* Previously (wretch@1) */
  3. wretch("...").get({ my: "option" })
  4. ```

This was a rarely used feature and the extra argument now appends a string to the base url.

  1. ``` js
  2. /* Now (wretch@2) */
  3. wretch("https://base.com").get("/resource/1")
  4. ```

Replay function


The .replay function has been renamed to [.fetch](https://elbywan.github.io/wretch/api/interfaces/index.Wretch.html#fetch).

License


MIT