HTTP client that uses the native fetch. Request is based on middlewares in order to extend the default fetch functionality.
Using npm:
$ npm install @workablehr/request
import request from "@workablehr/request";
const promise = request("resource.com"); // submits a get request to 'resource.com'
promise
.then(reponse => {
console.log("reponse", reponse);
})
.catch(error => {
console.error("error", error);
});
Request will resolve the promise if the response status is between 200 and 299. Otherwise, it will reject the promise. If the promise resolved successfully, it will return the JSON content of the response. If the promise rejected, it will return an error containing the response and an XHRHandler.
XHRHandler triggers callbacks according to http response rules.
XHRHandler.init(response).catch(error =>
error.asyncHandler.then(handler =>
handler
.when(400, () => "doSomething")
.whenNot(401, () => "doSomething")
.otherwise(() => "doSomething")
.always(() => "doSomething")
.handle()
)
);
- withAbort
- withCache
- withShortcuts
- withBgSync
Middleware is an easy way to extend the basic functionality of the request. For example, if you would like to create a request that can be aborted, you could merely do:
import basicRequest, { withAbort } from "@workablehr/request";
const request = withAbort(basicRequest);
const promise = request("resource.com", {
method: "POST",
body: JSON.stringify({ data })
});
promise.abort();
Or if you would like to use the shortcut request.post(), you could:
import basicRequest, { withAbort, withShortcuts } from "@workablehr/request";
const request = withShortcuts(withAbort(basicRequest));
const promise = request.post("resource.com", { data });
promise.abort();
You can find more information for each middleware on the corresponding file.
Injects an abort function in the request promise.
Caches a request in the indexed DB.
Extends the request method with post/put/del methods.
Sends the request to the service worker in order to perform it when the device is back online.
A middleware is nothing more than a simple function that accepts request method and returns the extended request.
import basicRequest from "@workablehr/request";
const withRequestLogger = request => {
return (url, params) => {
console.log("start request", url);
request(url, params).then(response => {
console.log("successfully request", url);
return response;
});
};
};
const request = withRequestLogger(basicRequest);