Constructor

RequestWrapper

new RequestWrapper(input)

Constructor for RequestWrapper.

Parameter

input

Object

Values in input have the following properties:

Parameter

cacheName

Optional

string

The name of the cache to use for Handlers that involve caching. If none is provided, a default name that includes the current service worker scope will be used.

plugins

Optional

Array of Object

Any plugins that should be invoked.

fetchOptions

Optional

Object

Values passed along to the init of all fetch() requests made by this wrapper.

matchOptions

Optional

Object

Values passed along to the options of all cache match() requests made by this wrapper.

Methods

fetch

async

fetch(input) returns Promise containing Response

Wraps fetch(), calls all requestWillFetch before making the network request, and calls any fetchDidFail callbacks from the registered plugins if the request fails.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

(Request or string)

The request or URL to be fetched.

Returns

Promise containing Response The network response.

Example

requestWrapper.fetch({
  request: event.request
})
.then((response) => {
 ...
})
.catch((err) => {
  ...
});

fetchAndCache

async

fetchAndCache(input) returns Promise containing Response

Combines both fetching and caching using the previously configured options and calling the appropriate plugins.

By default, responses with a status of 2xx will be considered valid and cacheable, but this could be overridden by configuring one or more plugins that implement the cacheWillUpdate lifecycle callback.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

Request

The request to fetch.

waitOnCache

Optional

boolean

true means the method should wait for the cache.put() to complete before returning. The default value of false means return without waiting. It this value is true and the response can't be cached, an error will be thrown.

cacheKey

Optional

Request

Supply a cacheKey if you wish to cache the response against an alternative request to the request argument.

cacheResponsePlugin

Optional

function()

Allows the caller to override the default check for cacheability, for situations in which the cacheability check wasn't explicitly configured when constructing the RequestWrapper.

cleanRedirects

Optional

boolean

If true, a "clean" copy of any redirected responses will be added to the cache, since redirected responses can't be used to satisfy navigation requests. Defaults to false.

Returns

Promise containing Response The network response.

Example

requestWrapper.fetchAndCache({
  request: event.request
})
.then((response) => {
 ...
})
.catch((err) => {
  ...
});

getCache

async

getCache() returns Promise containing Cache

Opens a cache and maintains a reference to that cache for future use.

Returns

Promise containing Cache An open Cache instance based on the configured cacheName.

Example

requestWrapper.getCache()
.then((openCache) => {
   ...
});

match

async

match(input) returns Promise containing Response

Wraps cache.match(), using the previously configured cache name and match options.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

(Request or string)

The key for the cache lookup.

Returns

Promise containing Response The cached response.

Example

requestWrapper.match({event.request})
.then((response) => {
  if (!response) {
    // No response in cache.
    return;
  }
  ...
});

Abstract types

cacheDidUpdate

static

cacheDidUpdate(input)

Called after a response has been written to the cache.

Parameter

input

Object

Values in input have the following properties:

Parameter

cacheName

String

The name of the cache that was updated.

url

String

The URL used as a key for the cache.

oldResponse

(Response or null)

The response that was previously in the cache, prior to the update, or null if the cache didn't previously contain an entry for url.

newResponse

(Response or null)

The response that was written to the cache.

Example

Logs a message when the cache has been updated.

async function cacheDidUpdate({cacheName, url}) {
  console.log(`The entry for ${url} in cache ${cacheName} was updated.`);
}

cachedResponseWillBeUsed

static

cachedResponseWillBeUsed(input) returns Promise containing (Response or null)

Called before a previously cached response that has been read from the cache is used. This allows you to modify it or return null if it's not valid.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

Request

The original request.

cache

Cache

An open instance of the cache.

cacheName

String

The name corresponding to cache.

cachedResponse

(Response or null)

The response for request that's currently in cache, or null if there isn't currently a response cached.

matchOptions

Object

The cache match options that were configured when the current RequestWrapper was constructed.

Returns

Promise containing (Response or null) The response to be used as the effective cache match. This might be the same response as cachedResponse, if it was valid, a modified version of the response, or null if there's no valid match.

Example

<caption>Returns `null` to indicate that a cached response shouldn't
be used if its Date header is too far in the past.</caption>

async function cachedResponseWillBeUsed({cachedResponse}) {
  if (cachedResponse) {
    const dateHeader = cachedResponse.headers.get('date');
    const date = new Date(dateHeader);
    if (dateHeader && (Date.now() - date.getTime()) < 1000) {
      return cachedResponse;
    }
  }

  return null;
}

cacheWillUpdate

static

cacheWillUpdate(input) returns Promise containing Boolean

Called prior to a response being written to the cache. This allows you to prevent the cache from being updated if the response doesn't meet your custom criteria.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

Request

The original request.

response

Response

The response to the request, based on the configured strategy.

Returns

Promise containing Boolean true if the response meets your criteria for being added to the appropriate cache, and false if it doesn't.

Example

<caption>Determines whether a response is cacheable based on
whether its Cache-Control header contains the string 'no-cache'.</caption>

async function cacheWillUpdate({response}) {
  return !response.headers.get('cache-control').includes('no-cache');
}

fetchDidFail

static

fetchDidFail(input)

Called after a network request has failed. This allows you to report the failure, or save a copy of the failed request to be retried later.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

Request

A clone of the request that failed. You can consume the request's body if needed.

Example

Logs a message when a network request fails.

async function fetchDidFail({request}) {
  const body = await request.text();
  console.log(`A request for ${request.url} with body ${body} failed.`);
}

requestWillFetch

static

requestWillFetch(input) returns Promise containing Request

Called prior to a network request being made. This allows you to update the request's URL or headers as appropriate, or just return the original request if there are no modifications needed.

Parameter

input

Object

Values in input have the following properties:

Parameter

request

Request

The request that would otherwise have been made against the network.

Returns

Promise containing Request The request that will be used against the network instead.

Example

Appends a URL parameter to all outgoing requests.

async function requestWillFetch({request}) {
  const url = new URL(request.url);
  url.searchParams.set('from-workbox', 'true');
  return new Request(url.href, {headers: request.headers});
}