Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds makeRequest() method to workbox.strategies #1408

Merged
merged 2 commits into from
Apr 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 56 additions & 19 deletions packages/workbox-strategies/CacheFirst.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2016 Google Inc. All Rights Reserved.
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -26,21 +26,19 @@ import './_version.mjs';
* An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network}
* request strategy.
*
* A cache first strategy is useful for assets that have beeng revisioned,
* A cache first strategy is useful for assets that have been revisioned,
* such as URLs like `/styles/example.a8f5f1.css`, since they
* can be cached for long periods of time.
*
* @memberof workbox.strategies
*/
class CacheFirst {
// TODO: Replace `plugins` parameter link with link to d.g.c.

/**
* @param {Object} options
* @param {string} options.cacheName Cache name to store and retrieve
* requests. Defaults to cache names provided by
* [workbox-core]{@link workbox.core.cacheNames}.
* @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
* @param {string} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
* to use in conjunction with this caching strategy.
* @param {Object} options.fetchOptions Values passed along to the
* [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
Expand All @@ -63,7 +61,6 @@ class CacheFirst {
* @return {Promise<Response>}
*/
async handle({event}) {
const logs = [];
if (process.env.NODE_ENV !== 'production') {
assert.isInstance(event, FetchEvent, {
moduleName: 'workbox-strategies',
Expand All @@ -73,9 +70,46 @@ class CacheFirst {
});
}

return this.makeRequest({
event,
request: event.request,
});
}

/**
* This method can be used to perform a make a standalone request outside the
* context of the [Workbox Router]{@link workbox.routing.Router}.
*
* See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
* for more usage information.
*
* @param {Object} input
* @param {Request|string} input.request Either a
* [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
* object, or a string URL, corresponding to the request to be made.
* @param {FetchEvent} [input.event] If provided, `event.waitUntil()` will be
* called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}) {
const logs = [];

if (typeof request === 'string') {
request = new Request(request);
}

if (process.env.NODE_ENV !== 'production') {
assert.isInstance(request, Request, {
moduleName: 'workbox-strategies',
className: 'CacheFirst',
funcName: 'makeRequest',
paramName: 'request',
});
}

let response = await cacheWrapper.match(
this._cacheName,
event.request,
request,
null,
this._plugins
);
Expand All @@ -88,7 +122,7 @@ class CacheFirst {
`Will respond with a network request.`);
}
try {
response = await this._getFromNetwork(event);
response = await this._getFromNetwork(request, event);
} catch (err) {
error = err;
}
Expand All @@ -109,7 +143,7 @@ class CacheFirst {

if (process.env.NODE_ENV !== 'production') {
logger.groupCollapsed(
messages.strategyStart('CacheFirst', event));
messages.strategyStart('CacheFirst', request));
for (let log of logs) {
logger.log(log);
}
Expand All @@ -129,29 +163,32 @@ class CacheFirst {
/**
* Handles the network and cache part of CacheFirst.
*
* @param {FetchEvent} event
* @param {Request} request
* @param {FetchEvent} [event]
* @return {Promise<Response>}
*
* @private
*/
async _getFromNetwork(event) {
async _getFromNetwork(request, event) {
const response = await fetchWrapper.fetch(
event.request,
request,
this._fetchOptions,
this._plugins
);

// Keep the service worker while we put the request to the cache
const responseClone = response.clone();
event.waitUntil(
cacheWrapper.put(
this._cacheName,
event.request,
responseClone,
this._plugins
)
const cachePutPromise = cacheWrapper.put(
this._cacheName,
request,
responseClone,
this._plugins
);

if (event) {
event.waitUntil(cachePutPromise);
}

return response;
}
}
Expand Down
48 changes: 40 additions & 8 deletions packages/workbox-strategies/CacheOnly.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2016 Google Inc. All Rights Reserved.
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -21,16 +21,13 @@ import {logger} from 'workbox-core/_private/logger.mjs';
import messages from './utils/messages.mjs';
import './_version.mjs';

// TODO: Replace `Workbox plugins` link in the class description with a
// link to d.g.c.
// TODO: Replace `plugins` parameter link with link to d.g.c.

/**
* An implementation of a
* [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only}
* request strategy.
*
* This class is useful if you want to take advantage of any [Workbox plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}.
* This class is useful if you want to take advantage of any [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}.
*
* @memberof workbox.strategies
*/
Expand All @@ -40,7 +37,7 @@ class CacheOnly {
* @param {string} options.cacheName Cache name to store and retrieve
* requests. Defaults to cache names provided by
* [workbox-core]{@link workbox.core.cacheNames}.
* @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
* @param {string} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
* to use in conjunction with this caching strategy.
*/
constructor(options = {}) {
Expand Down Expand Up @@ -68,16 +65,51 @@ class CacheOnly {
});
}

return this.makeRequest({
event,
request: event.request,
});
}

/**
* This method can be used to perform a make a standalone request outside the
* context of the [Workbox Router]{@link workbox.routing.Router}.
*
* See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
* for more usage information.
*
* @param {Object} input
* @param {Request|string} input.request Either a
* [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
* object, or a string URL, corresponding to the request to be made.
* @param {FetchEvent} [input.event] If provided, `event.waitUntil()` will be
* called automatically to extend the service worker's lifetime.
* @return {Promise<Response>}
*/
async makeRequest({event, request}) {
if (typeof request === 'string') {
request = new Request(request);
}

if (process.env.NODE_ENV !== 'production') {
assert.isInstance(request, Request, {
moduleName: 'workbox-strategies',
className: 'CacheOnly',
funcName: 'makeRequest',
paramName: 'request',
});
}

const response = await cacheWrapper.match(
this._cacheName,
event.request,
request,
null,
this._plugins
);

if (process.env.NODE_ENV !== 'production') {
logger.groupCollapsed(
messages.strategyStart('CacheOnly', event));
messages.strategyStart('CacheOnly', request));
if (response) {
logger.log(`Found a cached response in the '${this._cacheName}'` +
` cache.`);
Expand Down
Loading