RequestWrapper

This class is used by the various subclasses of Handler to configure the cache name and any desired plugins, which is to say classes that implement request lifecycle callbacks.

It automatically triggers any registered callbacks at the appropriate time.

Constructor

new RequestWrapper(input)

Constructor for RequestWrapper.

Parameters
input Object
Properties
cacheName string (Optional)

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 Array.<Object> (Optional)

Any plugins that should be invoked.

fetchOptions Object (Optional)

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

matchOptions Object (Optional)

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

Instance Methods

this.fetch(input) Promise.<Response>

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

Example
requestWrapper.fetch({
  request: event.request
})
.then((response) => {
 ...
})
.catch((err) => {
  ...
});
Parameters
input Object
Properties
request Request | string

The request or URL to be fetched.

Returns Promise.<Response>

The network response.

this.fetchAndCache(input) Promise.<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.

Example
requestWrapper.fetchAndCache({
  request: event.request
})
.then((response) => {
 ...
})
.catch((err) => {
  ...
});
Parameters
input Object
Properties
request Request

The request to fetch.

waitOnCache boolean (Optional)

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 Request (Optional)

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

cacheResponsePlugin function (Optional)

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 boolean (Optional)

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.<Response>

The network response.

this.getCache() Promise.<Cache>

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

Example
requestWrapper.getCache()
.then((openCache) => {
   ...
});
Returns Promise.<Cache>

An open Cache instance based on the configured cacheName.

this.match(input) Promise.<Response>

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

Example
requestWrapper.match({event.request})
.then((response) => {
  if (!response) {
    // No response in cache.
    return;
  }
  ...
});
Parameters
input Object
Properties
request Request | string

The key for the cache lookup.

Returns Promise.<Response>

The cached response.

Type Definitions

this.cacheDidUpdate(input)

Called after a response has been 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.`);
}
Parameters
input Object
Properties
cacheName String

The name of the cache that was updated.

url String

The URL used as a key for the cache.

oldResponse Response | 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 | null

The response that was written to the cache.

this.cachedResponseWillBeUsed(input) Promise.<(Response|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.

Example

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

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;
}
Parameters
input Object
Properties
request Request

The original request.

cache Cache

An open instance of the cache.

cacheName String

The name corresponding to cache.

cachedResponse Response | 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.<(Response|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.

this.cacheWillUpdate(input) Promise.<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.

Example

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

async function cacheWillUpdate({response}) {
  return !response.headers.get('cache-control').includes('no-cache');
}
Parameters
input Object
Properties
request Request

The original request.

response Response

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

Returns Promise.<Boolean>

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

this.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.

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.`);
}
Parameters
input Object
Properties
request Request

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

this.requestWillFetch(input) Promise.<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.

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});
}
Parameters
input Object
Properties
request Request

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

Returns Promise.<Request>

The request that will be used against the network instead.