Wretch 1.7 is now live π ! Please check out 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.
A collection of middlewares is available through the wretch-middlewares package! π¦
// 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 => /* ... */)
// Wretch object is immutable which means that you can configure, store and reuse instances
// Cross origin authenticated requests on an external API
const externalApi = wretch()
// Set the base url
.url("http://external.api")
// Authorization header
.auth(`Bearer ${ token }`)
// Cors fetch options
.options({ credentials: "include", mode: "cors" })
// Handle 403 errors
.resolve(_ => _.forbidden(handle403))
// Fetch a resource
externalApi
.url("/resource/1")
// Add a custom header for this request
.headers({ "If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT" })
.get()
.json(handleResource)
// Post a resource
externalApi
.url("/resource")
.post({ "Shiny new": "resource object" })
.json(handleNewResourceResult)
npm i wretch
git clone https://github.com/elbywan/wretch
cd wretch
npm install
npm start
Wretch is compatible with modern browsers out of the box.
For older environments without fetch support, you should get a polyfill.
Works with any FormData or fetch polyfills.
// The global way :
global.fetch = require("node-fetch")
global.FormData = require("form-data")
global.URLSearchParams = require("url").URLSearchParams
// Or the non-global way :
wretch().polyfills({
fetch: require("node-fetch"),
FormData: require("form-data"),
URLSearchParams: require("url").URLSearchParams
})
Works with Deno >= 0.41.0 out of the box.
// You can import wretch from any CDN that serve ESModules.
import wretch from 'https://cdn.pika.dev/wretch'
const text = await wretch('https://httpstat.us/200').get().text()
console.log(text) // -> 200 OK
This project uses automated node.js & browser unit tests. The latter are a provided courtesy of:
Wretch is bundled using the UMD format (@dist/bundle/wretch.js
), ESM format (@dist/bundle/wretch.esm.js
) alongside es2015 modules (@dist/index.js
) and typescript definitions.
<!--- "wretch" will be attached to the global window object. -->
<script src="https://unpkg.com/wretch"></script>
// es2015 modules
import wretch from "wretch"
// commonjs
var wretch = require("wretch")
Wretcher objects are immutable.
wretch(url, options)
/* The "request" chain. */
.[helper method(s)]()
// [ Optional ]
// A set of helper methods to set the default options, set accept header, change the current url ...
.[body type]()
// [ Optional ]
// Serialize an object to json or FormData formats and sets the body & header field if needed
.[http method]()
// [ Required, ends the request chain ]
// Performs the get/put/post/delete/patch request
/* Fetch is called at this time. */
/* The request is sent, and from this point on you can chain catchers and call a response type handler. */
/* The "response" chain. */
.[catcher(s)]()
// [ Optional ]
// You can chain error handlers here
.[response type]()
// [ Required, ends the response chain ]
// Specify the data type you need, which will be parsed and handed to you
/* From this point wretch returns a standard Promise, so you can continue chaining actions afterwards. */
.then(/* ... */)
.catch(/* ... */)
Creates a new Wretcher object with an url and vanilla fetch options.
Helper methods are optional and can be chained.
url | query | options | headers | accept | content | auth | catcher | resolve | defer | defaults | errorType | polyfills |
---|
Appends or replaces the url.
wretch().url("...").get().json(/* ... */)
// Can be used to set a base url
// Subsequent requests made using the 'blogs' object will be prefixed with "http://mywebsite.org/api/blogs"
const blogs = wretch("http://mywebsite.org/api/blogs")
// Perfect for CRUD apis
const id = await blogs.post({ name: "my blog" }).json(_ => _.id)
const blog = await blogs.url(`/${id}`).get().json()
console.log(blog.name)
await blogs.url(`/${id}`).delete().res()
// And to replace the base url if needed :
const noMoreBlogs = blogs.url("http://mywebsite.org/", true)
Converts a javascript object to query parameters, then appends this query string to the current url. String values are used as the query string verbatim.
Pass true
as the second argument to replace existing query parameters.
let w = wretch("http://example.com")
// url is http://example.com
w = w.query({ a: 1, b: 2 })
// url is now http://example.com?a=1&b=2
w = w.query({ c: 3, d: [4, 5] })
// url is now http://example.com?a=1&b=2c=3&d=4&d=5
w = w.query("five&six&seven=eight")
// url is now http://example.com?a=1&b=2c=3&d=4&d=5&five&six&seven=eight
w = w.query({ reset: true }, true)
// url is now http://example.com?reset=true
For this kind of usage, you can use wretch
in conjunction with other libraries (like qs
).
/* Using wretch with qs */
const queryObject = { some: { nested: 'objects' }}
// Use .qs inside .query :
wretch("https://example.com/").query(qs.stringify(queryObject))
// Use .defer :
const qsWretch = wretch().defer((w, url, { qsQuery, qsOptions }) => (
qsQuery ? w.query(qs.stringify(qsQuery, qsOptions)) : w
))
qsWretch
.url("https://example.com/")
.options({ qs: {Β query: queryObject }})
/* ... */
Sets the fetch options.
wretch("...").options({ credentials: "same-origin" })
Wretch being immutable, you can store the object for later use.
const corsWretch = wretch().options({ credentials: "include", mode: "cors" })
corsWretch.url("http://endpoint1").get()
corsWretch.url("http://endpoint2").get()
You can override instead of mixing in the existing options by passing a boolean flag.
// By default options mixed in :
wretch()
.options({ headers: { "Accept": "application/json" }})
.options({ encoding: "same-origin", headers: { "X-Custom": "Header" }})
/*
{
headers: { "Accept": "application/json", "X-Custom": "Header" },
encoding: "same-origin"
}
*/
// With the flag, options are overridden :
wretch()
.options({ headers: { "Accept": "application/json" }})
.options({ encoding: "same-origin", headers: { "X-Custom": "Header" }}, false)
/*
{
headers: { "X-Custom": "Header" },
encoding: "same-origin"
}
*/
Sets the request headers.
wretch("...")
.headers({ "Content-Type": "text/plain", Accept: "application/json" })
.post("my text")
.json()
Shortcut to set the "Accept" header.
wretch("...").accept("application/json")
Shortcut to set the "Content-Type" header.
wretch("...").content("application/json")
Shortcut to set the "Authorization" header.
wretch("...").auth("Basic d3JldGNoOnJvY2tz")
catcher(errorId: number | string, catcher: (error: WretcherError, originalRequest: Wretcher) => void)
Adds a catcher which will be called on every subsequent request error.
Very useful when you need to perform a repetitive action on a specific error code.
const w = wretch()
.catcher(404, err => redirect("/routes/notfound", err.message))
.catcher(500, err => flashMessage("internal.server.error"))
// No need to catch the 404 or 500 codes, they are already taken care of.
w.url("http://myapi.com/get/something").get().json(json => /* ... */)
// Default catchers can be overridden if needed.
w
.url("http://myapi.com/get/something")
.get()
.notFound(err => /* overrides the default 'redirect' catcher */)
.json(json => /* ... */)
The original request is passed along the error and can be used in order to perform an additional request.
const reAuthOn401 = wretch()
.catcher(401, async (error, request) => {
// Renew credentials
const token = await wretch("/renewtoken").get().text()
storeToken(token)
// Replay the original request with new credentials
return request.auth(token).replay().unauthorized(err => {Β throw err }).json()
})
reAuthOn401.url("/resource")
.get()
.json() // <- Will only be called for the original promise
.then(callback) // <- Will be called for the original OR the replayed promise result
defer(callback: (originalRequest: Wretcher, url: string, options: Object) => Wretcher, clear = false)
Defer wretcher methods that will be chained and called just before the request is performed.
/* Small fictional example: deferred authentication */
// If you cannot retrieve the auth token while configuring the wretch object you can use .defer to postpone the call
const api = wretch("...").defer((w, url, options) => {
// If we are hitting the route /userβ¦
if(/\/user/.test(url)) {
const { token } = options.context
return w.auth(token)
}
return w
})
// ... //
const token = await getToken(request.session.user)
// .auth gets called here automatically
api.options({
context: { token }
}).get().res()
resolve(doResolve: (chain: ResponseChain, originalRequest: Wretcher) => ResponseChain | Promise, clear = false)
Programs a resolver which will automatically be injected to perform response chain tasks.
Very useful when you need to perform repetitive actions on the wretch response.
The clear argument, if set to true, removes previously defined resolvers.
// Program "response" chain actions early on
const w = wretch()
.resolve(resolver => resolver
.perfs(_ => /* monitor every request */)
.json(_ => _ /* automatically parse and return json */))
const myJson = await w.url("http://a.com").get()
// Equivalent to wretch()
// .url("http://a.com")
// .get()
// <- the resolver chain is automatically injected here !
// .perfs(_ => /* ... */)
// .json(_ => _)
Sets default fetch options which will be used for every subsequent requests.
// Interestingly enough, default options are mixed in :
wretch().defaults({ headers: { "Accept": "application/json" }})
// The fetch request is sent with both headers.
wretch("...", { headers: {Β "X-Custom": "Header" }}).get()
// You can mix in with the existing options instead of overriding them by passing a boolean flag :
wretch().defaults({ headers: { "Accept": "application/json" }})
wretch().defaults({ encoding: "same-origin", headers: { "X-Custom": "Header" }}, true)
/* The new options are :
{
headers: { "Accept": "application/json", "X-Custom": "Header" },
encoding: "same-origin"
}
*/
Sets the method (text, json ...) used to parse the data contained in the response body in case of an HTTP error.
Persists for every subsequent requests.
wretch().errorType("json")
wretch("http://server/which/returns/an/error/with/a/json/body")
.get()
.res()
.catch(error => {
// error[errorType] (here, json) contains the parsed body
console.log(error.json))
}
Sets the non-global polyfills which will be used for every subsequent calls.
const fetch = require("node-fetch")
const FormData = require("form-data")
wretch().polyfills({
fetch: fetch,
FormData: FormData,
URLSearchParams: require("url").URLSearchParams
})
A body type is only needed when performing put/patch/post requests with a body.
body | json | formData | formUrl |
---|
Sets the request body with any content.
wretch("...").body("hello").put()
// Note that calling an 'http verb' method with the body as an argument is equivalent:
wretch("...").put("hello")
Sets the content type header, stringifies an object and sets the request body.
const jsonObject = { a: 1, b: 2, c: 3 }
wretch("...").json(jsonObject).post()
// Note that calling an 'http verb' method with the object body as an argument is equivalent:
wretch("...").post(jsonObject)
Converts the javascript object to a FormData and sets the request body.
const form = {
hello: "world",
duck: "Muscovy"
}
wretch("...").formData(form).post()
The recursive
argument when set to true
will enable recursion through all nested objects and produce object[key]
keys.
It can be set to an array of string to exclude specific keys.
Warning: Be careful to exclude
Blob
instances in the Browser, andReadableStream
andBuffer
instances when using the node.js compatibleform-data
package.
const form = {
duck: "Muscovy",
duckProperties: {
beak: {
color: "yellow"
},
legs: 2
},
ignored: {
key: 0
}
}
// Will append the following keys to the FormData payload:
// "duck", "duckProperties[beak][color]", "duckProperties[legs]"
wretch("...").formData(form, ["ignored"]).post()
Converts the input parameter to an url encoded string and sets the content-type header and body. If the input argument is already a string, skips the conversion part.
const form = { a: 1, b: { c: 2 }}
const alreadyEncodedForm = "a=1&b=%7B%22c%22%3A2%7D"
// Automatically sets the content-type header to "application/x-www-form-urlencoded"
wretch("...").formUrl(form).post()
wretch("...").formUrl(alreadyEncodedForm).post()
Required
You can pass optional fetch options and body arguments to these methods as a shorthand.
// This shorthand:
wretch().post({ json: 'body' }, { credentials: "same-origin" })
// Is equivalent to:
wretch().json({Β json: 'body'}).options({ credentials: "same-origin" }).post()
NOTE: For methods having a body argument if the value is an Object
it is assumed that it is a JSON payload and apply the same behaviour
as calling .json(body)
, unless the Content-Type
header has been set to something else beforehand.
get | delete | put | patch | post | head | opts |
---|
Performs a get request.
wretch("...").get()
Performs a delete request.
wretch("...").delete()
Performs a put request.
wretch("...").json({...}).put()
Performs a patch request.
wretch("...").json({...}).patch()
Performs a post request.
wretch("...").json({...}).post()
Performs a head request.
wretch("...").head()
Performs an options request.
wretch("...").opts()
Catchers are optional, but if you do not provide them an error will still be thrown in case of an http error code received.
Catchers can be chained.
badRequest | unauthorized | forbidden | notFound | timeout | internalError | error | fetchError |
---|
type WretcherError = Error & { status: number, response: WretcherResponse, text?: string, json?: Object }
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()
Syntactic sugar for error(400, cb)
.
Syntactic sugar for error(401, cb)
.
Syntactic sugar for error(403, cb)
.
Syntactic sugar for error(404, cb)
.
Syntactic sugar for error(408, cb)
.
Syntactic sugar for error(500, cb)
.
Catches a specific error given its code or name and perform the callback.
Catches any error thrown by the fetch function and perform the callback.
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)
Required
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 passsed to the Promise
wretch("...").get().json(() => "Hello world!").then(console.log) // Hello world!
If an error is caught by catchers, the response type handler will not be called.
res | json | blob | formData | arrayBuffer | text |
---|
Raw Response handler.
wretch("...").get().res(response => console.log(response.url))
Json handler.
wretch("...").get().json(json => console.log(Object.keys(json)))
Blob handler.
wretch("...").get().blob(blob => /* ... */)
FormData handler.
wretch("...").get().formData(formData => /* ... */)
ArrayBuffer handler.
wretch("...").get().arrayBuffer(arrayBuffer => /* ... */)
Text handler.
wretch("...").get().text(txt => console.log(txt))
A set of extra features.
Abortable requests | Performance API | Middlewares |
---|
Only compatible with browsers that support AbortControllers. Otherwise, you could use a (partial) polyfill.
Use case :
const [c, w] = wretch("...")
.get()
.onAbort(_ => console.log("Aborted !"))
.controller()
w.text(_ => console.log("should never be called"))
c.abort()
// Or :
const controller = new AbortController()
wretch("...")
.signal(controller)
.get()
.onAbort(_ => console.log("Aborted !"))
.text(_ => console.log("should never be called"))
c.abort()
Used at "request time", like an helper.
Associates a custom controller with the request. Useful when you need to use your own AbortController, otherwise wretch will create a new controller itself.
const controller = new AbortController()
// Associates the same controller with multiple requests
wretch("url1")
.signal(controller)
.get()
.json(_ => /* ... */)
wretch("url2")
.signal(controller)
.get()
.json(_ => /* ... */)
// Aborts both requests
controller.abort()
Used at "response time".
Aborts the request after a fixed time. If you use a custom AbortController associated with the request, pass it as the second argument.
// 1 second timeout
wretch("...").get().setTimeout(1000).json(_ => /* will not be called in case of a timeout */)
Used at "response time".
Returns the automatically generated AbortController alongside the current wretch response as a pair.
// We need the controller outside the chain
const [c, w] = wretch("url")
.get()
.controller()
// Resume with the chain
w.onAbort(_ => console.log("ouch")).json(_ => /* ... */)
/* Later on ... */
c.abort()
Used at "response time" like a catcher.
Catches an AbortError and performs the callback.
Takes advantage of the Performance API (browsers & node.js) to expose timings related to the underlying request.
Browser timings are very accurate, node.js only contains raw measures.
// Use perfs() before the response types (text, json, ...)
wretch("...")
.get()
.perfs(timings => {
/* Will be called when the timings are ready. */
console.log(timings.startTime)
})
.res()
/* ... */
For node.js, there is a little extra work to do :
// Node.js 8.5+ only
const { performance, PerformanceObserver } = require("perf_hooks")
wretch().polyfills({
fetch: function(url, opts) {
performance.mark(url + " - begin")
return fetch(url, opts).then(_ => {
performance.mark(url + " - end")
performance.measure(_.url, url + " - begin", url + " - end")
})
},
/* other polyfills ... */
performance: performance,
PerformanceObserver: PerformanceObserver
})
Middlewares are functions that can intercept requests before being processed by Fetch. Wretch includes a helper to help replicate the middleware style.
Check out wretch-middlewares, the official collection of middlewares.
Basically a Middleware is a function having the following signature :
// A middleware accepts options and returns a configured version
type Middleware = (options?: {[key: string]: any}) => ConfiguredMiddleware
// A configured middleware (with options curried)
type ConfiguredMiddleware = (next: FetchLike) => FetchLike
// A "fetch like" function, accepting an url and fetch options and returning a response promise
type FetchLike = (url: string, opts: WretcherOptions) => Promise<WretcherResponse>
Add middlewares to intercept a request before being sent.
/* A simple delay middleware. */
const delayMiddleware = delay => next => (url, opts) => {
return new Promise(res => setTimeout(() => res(next(url, opts)), delay))
}
// The request will be delayed by 1 second.
wretch("...").middlewares([
delayMiddleware(1000)
]).get().res(_ => /* ... */)
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.
const contextMiddleware = next => (url, opts) => {
if(opts.context) {
// Mutate "context"
opts.context.property = "anything"
}
return next(url, opts)
}
// Provide the reference to a "context" object
const context = {}
const res = await wretch("...")
// Pass "context" by reference as an option
.options({ context })
.middlewares([ contextMiddleware ])
.get()
.res()
console.log(context.property) // prints "anything"
/* A simple delay middleware. */
const delayMiddleware = delay => next => (url, opts) => {
return new Promise(res => setTimeout(() => res(next(url, opts)), delay))
}
/* Returns the url and method without performing an actual request. */
const shortCircuitMiddleware = () => next => (url, opts) => {
// We create a new Response object to comply because wretch expects that from fetch.
const response = new Response()
response.text = () => Promise.resolve(opts.method + "@" + url)
response.json = () => Promise.resolve({ url, method: opts.method })
// Instead of calling next(), returning a Response Promise bypasses the rest of the chain.
return Promise.resolve(response)
}
/* Logs all requests passing through. */
const logMiddleware = () => next => (url, opts) => {
console.log(opts.method + "@" + url)
return next(url, opts)
}
/* A throttling cache. */
const cacheMiddleware = (throttle = 0) => {
const cache = new Map()
const inflight = new Map()
const throttling = new Set()
return next => (url, opts) => {
const key = opts.method + "@" + url
if(!opts.noCache && throttling.has(key)) {
// If the cache contains a previous response and we are throttling, serve it and bypass the chain.
if(cache.has(key))
return Promise.resolve(cache.get(key).clone())
// If the request in already in-flight, wait until it is resolved
else if(inflight.has(key)) {
return new Promise((resolve, reject) => {
inflight.get(key).push([resolve, reject])
})
}
}
// Init. the pending promises Map
if(!inflight.has(key))
inflight.set(key, [])
// If we are not throttling, activate the throttle for X milliseconds
if(throttle && !throttling.has(key)) {
throttling.add(key)
setTimeout(() => { throttling.delete(key) }, throttle)
}
// We call the next middleware in the chain.
return next(url, opts)
.then(_ => {
// Add a cloned response to the cache
cache.set(key, _.clone())
// Resolve pending promises
inflight.get(key).forEach((([resolve, reject]) => resolve(_.clone()))
// Remove the inflight pending promises
inflight.delete(key)
// Return the original response
return _
})
.catch(_ => {
// Reject pending promises on error
inflight.get(key).forEach(([resolve, reject]) => reject(_))
inflight.delete(key)
throw _
})
}
}
// To call a single middleware
const cache = cacheMiddleware(1000)
wretch("...").middlewares([cache]).get()
// To chain middlewares
wretch("...").middlewares([
logMiddleware(),
delayMiddleware(1000),
shortCircuitMiddleware()
}).get().text(_ => console.log(text))
// To test the cache middleware more thoroughly
const wretchCache = wretch().middlewares([cacheMiddleware(1000)])
const printResource = (url, timeout = 0) =>
setTimeout(_ => wretchCache.url(url).get().notFound(console.error).text(console.log), timeout)
// The resource url, change it to an invalid route to check the error handling
const resourceUrl = "/"
// Only two actual requests are made here even though there are 30 calls
for(let i = 0; i < 10; i++) {
printResource(resourceUrl)
printResource(resourceUrl, 500)
printResource(resourceUrl, 1500)
}
MIT