- Notifications
You must be signed in to change notification settings - Fork6
✌️ Proxy fetch requests through the Background Sync API
License
sdgluck/fetch-background-sync
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Proxy fetch requests through theBackground Sync API
Made with ❤ at@outlandish
Fetch Sync allows you to proxy fetch requests through the Background Sync API so that they arehonoured if made when the UA is offline! Hooray!
Check out alive demo here.
- Make requests offline that will be sent when the UA regains connectivity (even if the web page is no longer open).
- Responses are forwarded back to the client as soon as they are received.
- Implements a familiar fetch-like API: similar function signature and the same return type (a Response).
- Make named requests that have their response stored in an IDBStore which you can collect in subsequent user sessions.
- Manage sync operations with
fetchSync.{get,getAll,cancel,cancelAll}()
. - Can be used with existing Service Worker infrastructures with
importScripts
, or handles SW registration for you. - If the browser does not support Background Sync, the library will fall back on normal
fetch
requests.
npm install fetch-sync --save
- Requirements
- Support
- Import
- Initialise
- Usage
- Sync API
- Dependencies
- Test
- Development
- Contributing
- Author & License
The library utilises some new technologies so currently only works in some browsers. It definitely works inChrome Canarywith theexperimental-web-platform-features
flag enabled.
The browser must support:
- Background Sync
- Service Worker
- Fetch
- IndexedDB
- [Promise] (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Chrome Canary | Chrome | Firefox | IE | Opera | Safari |
---|---|---|---|---|---|
✔ | ✔ | ✘ | ✘ | ✘ | ✘ |
Client
// ES6importfetchSyncfrom'fetch-sync'
// CommonJSvarfetchSync=require('fetch-sync')
<!-- Script, using minified dist --><scriptsrc="/node_modules/fetch-sync/dist/fetch-sync.min.js"></script>
Worker
SeeInitialise for details on importing and registering the service worker.
Existing Service Worker
If your application already uses a Service Worker, you can import the fetch-sync worker usingimportScripts
:
importScripts('node_modules/fetch-sync/dist/fetch-sync.sw.min.js')
And then callfetchSync.init()
somewhere in your application's initialisation procedure.
No Service Worker
fetch-sync can handle registration if you don't use a SW already...
Either serve the fetch-sync worker file with a header"Service-Worker-Allowed : /"
, or to avoid configuring headers,create a Service Worker script in the root of your project and use the method above for 'Existing Service Worker'.
Then see the example underUsage for thefetchSync.init()
method.
Initialise fetchSync.
- options {Object}(optional) options object
Look at the documentation forsw-register
available options and for more details on Service Worker registration.
Example:
// Import client lib...// ES6importfetchSyncfrom'fetch-sync'// ES5varfetchSync=require('fetch-sync')
<!-- Script, using bundled dist --><scriptsrc="/node_modules/fetch-sync/dist/fetch-sync.min.js"></script>
// Initialise, passing in worker lib location...fetchSync.init({url:'node_modules/fetch-sync/dist/fetch-sync.sw.js',scope:'<website address>'// e.g. 'http://localhost:8000'})
Perform async
Background Sync operation.
- [name] {String}(optional) name of the sync operation
- request {String|Request} URL or an instance of fetch Request
- [options] {Object}(optional)fetch options object
Returns a Promise that resolves on success of the fetch request. Rejects if a sync exists with this name already.
There are also some properties/methods on the Promise. See theSync API for more details.
If called with aname
:
- the response will be stored and can be retrieved later using e.g.
fetchSync.get('name').then(sync => sync.response)
. - the response will not automatically be removed from the IDBStore in the worker. You should requestthat a named sync be removed manually by using
sync.remove()
. - see theSync API for more details.
Examples:
named GET
fetchSync('GetMessages','/messages').then((response)=>response.json()).then((json)=>console.log(json.foo))
unnamed POST
constpost=fetchSync('/update-profile',{method:'POST',body:{name:''}})// cancel the sync...post.cancel()
unnamed with options
constheaders=newHeaders();headers.append('Authorization','Basic abcdefghijklmnopqrstuvwxyz');// `fetchSync` accepts the same args as `fetch`...fetchSync('/send-message',{ headers})
named with options
fetchSync('/get-messages',{ headers})
unnamed with Request
fetchSync(newRequest('/messages'))
Get a sync by its name.
- name {String} name of the sync operation to get
Returns a Promise that resolves with success of the sync operation or reject if sync operation is not found.
There are also some properties/methods on the Promise. See theSync API for more details.
Example:
fetchSync('SendMessage','/message',{body:'Hello, World!'})constsync=fetchSync.get('SendMessage')sync.then((response)=>{if(response.ok){alert(`Your message was received at${newDate(sync.syncedOn).toDateString()}.`}else{alert('Message failed to send.')}})
Get all sync operations.
Returns an array of all sync operations (named and unnamed).
Example:
fetchSync.getAll().then((syncs)=>syncs.forEach(sync=>sync.cancel()))
Cancel the sync with the givenname
.
- name {String} name of the sync operation to cancel
Example:
fetchSync('Update','/update',{ body})fetchSync.cancel('Update')
Cancel all syncs, named and unnamed.
Cancels the sync operation.
Returns a Promise of success of the cancellation.
Example:
constsync=fetchSync.get('Update')sync.cancel()
The unique ID of the sync operation. This will be its name if it has one.
The name of the sync operation if it has one.
The time that the sync operation was created.
The time that the sync operation was completed.
As the library depends on Service Workers and no headless browser has (good enough) support for Service Workersthat would allow tests to be executed within the console, tests are ran through the browser usingMocha andChai.
On runningnpm test
an Express server will be started atlocalhost:8000
.
Run the tests:
$cd fetch-sync$ npmtest
The library is bundled byWebpackand transpiled byBabel.
- Install dependencies:
npm install
- Start Webpack in a console:
npm run watch
- Start the test server in another:
npm test
- Navigate to
http://localhost:8000
All pull requests and issues welcome!
If you're not sure how, check out Kent C. Dodds'great video tutorials on egghead.io!
fetch-sync
was created bySam Gluck and is released under the MIT license.