Outbox
Outbox is an abstraction layer for sending ajax requests. It uses Fetch API as a default engine for sending the requests and Background Sync as a progressive enhancement if available.
Outbox uses exponential backoff as a retry strategy for failed requests (5xx status code or exception).
Why should I use it?
In every web application there are some requests that can treated in an asynchronous manner and that can happen in the background. Combined with the right user experience you can turn almost every request to an async background request. For example, you can let the user proceed with his/her doing right after clicking like/recommend/etc, making him/her thinking that everything worked but actually sending it in the background.
What is Background Sync?
Background Sync is a new web API that lets you defer actions until the user has stable connectivity. This is useful for ensuring that whatever the user wants to send, is actually sent. - Jake Archibald
Simply said you can use Background Sync to send requests even if the user has already closed your webapp, making sure that all the requests made their way to the server successfully.
Please note, this is still an experimental feature that might change.
How to use Outbox?
Install Outbox using bower:
bower install --save outbox
Import idb script and Outbox to your html:
<script src="bower_components/idb/lib/idb.js"></script>
<script src="bower_components/outbox/dist/browser/outbox.js"></script>
Now Outbox is exposed via window.outbox
, if you want to handle the responses received by Outbox set onResponse
property to a callback function:
window.outbox = (request, response) => {
};
request
contains the following properties:
-
path
the url of the request -
options
object which containsmethod
andbody
params
response
is a light version of the Response object, because
it is not possible to share a Reponse
object between service worker and client.
It assumes that the request body is a json an already parses it it using the json
function of Response
.
Adding a request is done simply by calling addRequest
method which takes path
, method
and body
as parameters.
window.outbox.addRequest('/api/method', 'POST', { key: 'value' });
The function returns a promise which resolves after the first attempt to dispatch the request no matter if it succeeded or failed.
Last but not least, you have to import the service worker script to your service worker. Add the following to your service worker javascript:
importScripts('/bower_components/outbox/dist/browser/sw.js');
Enjoy!