• Stars
    star
    127
  • Rank 281,165 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

โœŒ๏ธ Proxy fetch requests through the Background Sync API

fetch-sync

Proxy fetch requests through the Background Sync API

Made with โค at @outlandish

npm version js-standard-style

Fetch Sync allows you to proxy fetch requests through the Background Sync API so that they are honoured if made when the UA is offline! Hooray!

Check out a live 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.

Install

npm install fetch-sync --save

Table of Contents

Requirements

The library utilises some new technologies so currently only works in some browsers. It definitely works in Chrome Canary with the experimental-web-platform-features flag enabled.

The browser must support:

Support

Chrome Canary Chrome Firefox IE Opera Safari
โœ” โœ” โœ˜ โœ˜ โœ˜ โœ˜

Import

Client

// ES6
import fetchSync from 'fetch-sync'
// CommonJS
var fetchSync = require('fetch-sync')
<!-- Script, using minified dist -->
<script src="/node_modules/fetch-sync/dist/fetch-sync.min.js"></script>

Worker

See Initialise for details on importing and registering the service worker.

Initialise

Existing Service Worker

If your application already uses a Service Worker, you can import the fetch-sync worker using importScripts:

importScripts('node_modules/fetch-sync/dist/fetch-sync.sw.min.js')

And then call fetchSync.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 under Usage for the fetchSync.init() method.

Usage

fetchSync.init([options]) : Promise

Initialise fetchSync.

  • options {Object} (optional) options object

Look at the documentation for sw-register available options and for more details on Service Worker registration.

Example:

// Import client lib...

// ES6
import fetchSync from 'fetch-sync'

// ES5
var fetchSync = require('fetch-sync')
<!-- Script, using bundled dist -->
<script src="/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'
})

fetchSync([name, ]request[, options]) : Sync

Perform a sync 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 the Sync API for more details.

If called with a name:

  • 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 request that a named sync be removed manually by using sync.remove().
  • see the Sync API for more details.

Examples:

  • named GET

    fetchSync('GetMessages', '/messages')
      .then((response) => response.json())
      .then((json) => console.log(json.foo))
  • unnamed POST

    const post = fetchSync('/update-profile', {
      method: 'POST',
      body: { name: '' }
    })
    
    // cancel the sync...
    post.cancel()
  • unnamed with options

    const headers = new Headers();
    
    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(
      new Request('/messages')
    )

fetchSync.get(name) : Sync

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 the Sync API for more details.

Example:

fetchSync('SendMessage', '/message', { body: 'Hello, World!' })

const sync = fetchSync.get('SendMessage')

sync.then((response) => {
  if (response.ok) {
    alert(`Your message was received at ${new Date(sync.syncedOn).toDateString()}.`
  } else {
    alert('Message failed to send.')
  }
})

fetchSync.getAll() : Array<Sync>

Get all sync operations.

Returns an array of all sync operations (named and unnamed).

Example:

fetchSync.getAll()
  .then((syncs) => syncs.forEach(sync => sync.cancel()))

fetchSync.cancel(name) : Promise

Cancel the sync with the given name.

  • name {String} name of the sync operation to cancel

Example:

fetchSync('Update', '/update', { body })
fetchSync.cancel('Update')

fetchSync.cancelAll() : Promise

Cancel all syncs, named and unnamed.

Sync API

sync.cancel() : Promise

Cancels the sync operation.

Returns a Promise of success of the cancellation.

Example:

const sync = fetchSync.get('Update')
sync.cancel()

sync.id

The unique ID of the sync operation. This will be its name if it has one.

sync.name

The name of the sync operation if it has one.

sync.createdOn

The time that the sync operation was created.

sync.syncedOn

The time that the sync operation was completed.

Dependencies

Test

As the library depends on Service Workers and no headless browser has (good enough) support for Service Workers that would allow tests to be executed within the console, tests are ran through the browser using Mocha and Chai.

On running npm test an Express server will be started at localhost:8000.

Run the tests:

$ cd fetch-sync
$ npm test

Development

The library is bundled by Webpack and transpiled by Babel.

  • 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

Contributing

All pull requests and issues welcome!

If you're not sure how, check out Kent C. Dodds' great video tutorials on egghead.io!

Author & License

fetch-sync was created by Sam Gluck and is released under the MIT license.

More Repositories

1

mewt

๐ŸŒฑ Immutability in under one kilobyte
JavaScript
311
star
2

objecthistory

๐Ÿ€ Object undo, redo & change history using Proxies
JavaScript
58
star
3

msgr

๐Ÿ“ช Nifty service worker/client message utility
JavaScript
40
star
4

react-z-index

๐ŸŒ Easily manage global component z-index
JavaScript
24
star
5

carbonate

๐ŸŽจ colourful sprintf
JavaScript
22
star
6

werd

๐Ÿ“™ Words API for JavaScript w/ CLI (www.wordsapi.com)
JavaScript
21
star
7

tiny-tim

โณ a tiny timer < 160 bytes
JavaScript
21
star
8

cache-control

create cache-control headers
JavaScript
18
star
9

wait-for-decorator

โฐ Decorate a class method to return and wait on a Promise on the class instance before executing
JavaScript
16
star
10

daily-poem

๐Ÿ“– Read a new poem every day! (from http://poems.com)
JavaScript
12
star
11

react-floating-suffix

โ˜๏ธ Don't let that suffix outta sight!
JavaScript
12
star
12

sw-register

๐ŸŽฏ Service Worker registration utility
JavaScript
11
star
13

elquire

๐Ÿ Require local Node dependencies by a given name instead of a relative path
JavaScript
10
star
14

catch-and-match

๐Ÿ‰ Assert an error thrown (a)synchronously by a function.
JavaScript
6
star
15

require-global-node-module

Require a globally installed npm module
JavaScript
3
star
16

oss-licenses

๐Ÿ“„ A collection of OSS license texts
JavaScript
3
star
17

path-__dirname

Get a path in the __dirname
JavaScript
2
star
18

create-license

Create a LICENSE file
JavaScript
2
star
19

node-crossterm

Node bindings for Rust's crossterm
Rust
2
star
20

user-conf

Manage configs in the user home dir
JavaScript
2
star
21

path-homedir

Get a path in the user home directory
JavaScript
2
star
22

has-shebang

check if string or file contains shebang
JavaScript
2
star
23

path-cwd

Get a path in the cwd
JavaScript
2
star
24

error-clean-stack

throw errors with clean stacks
JavaScript
2
star
25

mini-defer

๐ŸŽ‰ Tiny module for creating a deferred with no polyfilling
JavaScript
1
star
26

sesd

๐Ÿ”๐Ÿ“œ Search esdiscuss.org topics
JavaScript
1
star
27

chain-call

๐Ÿ”— Build a chain of method calls
JavaScript
1
star
28

brolly

โ˜” Benchmark in style
JavaScript
1
star
29

posthog-nextjs-repro

CSS
1
star
30

i18n-squish

๐Ÿ“ฆ Watch and compile language files into single locales ready to be served with or without angular-translate
JavaScript
1
star
31

lodash-invariants

๐ŸŠ Invariants for lodash.is* methods
JavaScript
1
star
32

expand-top-level-dot-paths

Expand top-level object properties that are dot-paths
JavaScript
1
star
33

go-officialcharts

Unofficial go lib for scraping the UK singles charts from officialcharts.com
Go
1
star
34

test

JavaScript
1
star
35

markbody

๐Ÿ“ƒ Parse a webpage as markdown
JavaScript
1
star
36

webpack-get-dlls

Get DLL configs from a webpack config
JavaScript
1
star
37

argsy

๐Ÿ Awesome argument assertion
JavaScript
1
star
38

react-ref

๐Ÿ‘‰ Set reference to an element in React components
JavaScript
1
star
39

furck

๐Ÿด A better child_process.fork
JavaScript
1
star
40

require-local-node-module

Require a module from cwd's node_modules folder
JavaScript
1
star
41

serialise-response

๐Ÿ“ Serialise and deserialise a Fetch Response
JavaScript
1
star
42

series-logger

Log a series w/ spinner and op count
JavaScript
1
star
43

pick-to-array

๐Ÿœ Pick all values of a property in one or more objects
JavaScript
1
star
44

serialise-request

๐Ÿ“ Serialise and deserialise a Fetch Request
JavaScript
1
star
45

carbonate-logger

๐ŸŽจ๐Ÿ’ป Colourful console logs using carbonate
JavaScript
1
star