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

Make networkFirstResponse answer behaviour configurable #327

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
4 changes: 4 additions & 0 deletions docs/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ Allows you to adjust what and how to cache the assets.
> Default: `'all'`.


* `shouldServeFromNetwork`: `(response: Response, urlString: string, cacheUrl: string) => boolean`.
Allows to customize the behaviour when to fallback to a cached version of a resource if `responseStrategy: 'network-first'`.
Defaults to `(response) => response.ok`, meaning a response is only valid when the server returns a 2xx status code (see https://developer.mozilla.org/de/docs/Web/API/Response).

#### `AppCache: Object | null | false`

Settings for the `AppCache` cache. Use `null` or `false` to disable `AppCache` generation.
Expand Down
2 changes: 1 addition & 1 deletion lib/misc/sw-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ module.exports.pitch = function pitch(remainingRequest, precedingRequest, data)

var navigationPreloadCode = params.navigationPreload;

var helpersCode = [', {', 'loaders: ' + loadersCode + ',', 'cacheMaps: ' + cacheMapsCode + ',', 'navigationPreload: ' + navigationPreloadCode + ',', '}'];
var helpersCode = [', {', 'shouldServeFromNetwork: ' + params.shouldServeFromNetwork + ',', 'loaders: ' + loadersCode + ',', 'cacheMaps: ' + cacheMapsCode + ',', 'navigationPreload: ' + navigationPreloadCode + ',', '}'];

Promise.all([].concat(_toConsumableArray(modules.map(function (mod) {
return readFile(path.join(__dirname, mod));
Expand Down
9 changes: 8 additions & 1 deletion lib/misc/sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down
14 changes: 10 additions & 4 deletions lib/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ var _deepExtend2 = _interopRequireDefault(_deepExtend);

var _miscUtils = require('./misc/utils');

var REGEX_MINIFY_FUNC = /(\r\n|\n|\r|\s+)/gm;

var ServiceWorker = (function () {
function ServiceWorker(options) {
_classCallCheck(this, ServiceWorker);
Expand All @@ -37,7 +39,7 @@ var ServiceWorker = (function () {
this.minify = options.minify;
this.output = options.output.replace(/^\.\/+/, '');
this.publicPath = options.publicPath;

this.shouldServeFromNetwork = options.shouldServeFromNetwork;
this.basePath = null;
this.location = null;
this.pathRewrite = null;
Expand Down Expand Up @@ -76,6 +78,7 @@ var ServiceWorker = (function () {
var data = JSON.stringify({
data_var_name: this.SW_DATA_VAR,
cacheMaps: plugin.cacheMaps,
shouldServeFromNetwork: (0, _miscUtils.functionToString)(this.shouldServeFromNetwork),
navigationPreload: this.stringifyNavigationPreload(this.navigationPreload, plugin)
});

Expand Down Expand Up @@ -222,15 +225,16 @@ var ServiceWorker = (function () {
pluginVersion = plugin.pluginVersion;
}

return ('\n var ' + this.SW_DATA_VAR + ' = ' + JSON.stringify({
var loaders = Object.keys(plugin.loaders || {}).length ? plugin.loaders : void 0;

var result = ('\n var ' + this.SW_DATA_VAR + ' = ' + JSON.stringify({
assets: {
main: cache('main'),
additional: cache('additional'),
optional: cache('optional')
},

externals: externals,

hashesMap: hashesMap,

strategy: plugin.strategy,
Expand All @@ -241,12 +245,14 @@ var ServiceWorker = (function () {
relativePaths: plugin.relativePaths,

prefetchRequest: this.prefetchRequest,

loaders: loaders,
// These aren't added
alwaysRevalidate: plugin.alwaysRevalidate,
preferOnline: plugin.preferOnline,
ignoreSearch: plugin.ignoreSearch
}, null, minify ? void 0 : ' ') + ';\n ').trim();

return result;
}
}, {
key: 'getConfig',
Expand Down
3 changes: 2 additions & 1 deletion src/misc/sw-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ module.exports.pitch = function pitch(remainingRequest, precedingRequest, data)

const helpersCode = [
', {',
`shouldServeFromNetwork: ${params.shouldServeFromNetwork},`,
`loaders: ${loadersCode},`,
`cacheMaps: ${cacheMapsCode},`,
`navigationPreload: ${navigationPreloadCode},`,
Expand Down Expand Up @@ -90,4 +91,4 @@ function readFile(path) {
resolve(file);
});
});
}
}
11 changes: 9 additions & 2 deletions src/misc/sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -397,10 +397,17 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event)
.then((response) => {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', `URL [${ urlString }] from network`);
}
Expand Down Expand Up @@ -748,4 +755,4 @@ function logGroup(title, assets) {
});

console.groupEnd();
}
}
15 changes: 11 additions & 4 deletions src/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
isAbsolutePath, functionToString
} from './misc/utils';

const REGEX_MINIFY_FUNC = /(\r\n|\n|\r|\s+)/gm;

export default class ServiceWorker {
constructor(options) {
if (isAbsolutePath(options.output)) {
Expand All @@ -19,7 +21,7 @@ export default class ServiceWorker {
this.minify = options.minify;
this.output = options.output.replace(/^\.\/+/, '');
this.publicPath = options.publicPath;

this.shouldServeFromNetwork = options.shouldServeFromNetwork;
this.basePath = null;
this.location = null;
this.pathRewrite = null;
Expand Down Expand Up @@ -56,6 +58,7 @@ export default class ServiceWorker {
const data = JSON.stringify({
data_var_name: this.SW_DATA_VAR,
cacheMaps: plugin.cacheMaps,
shouldServeFromNetwork: functionToString(this.shouldServeFromNetwork),
navigationPreload: this.stringifyNavigationPreload(this.navigationPreload, plugin)
});

Expand Down Expand Up @@ -213,7 +216,10 @@ export default class ServiceWorker {
pluginVersion = plugin.pluginVersion;
}

return `
const loaders = Object.keys(plugin.loaders || {}).length ?
plugin.loaders : void 0;

const result = `
var ${ this.SW_DATA_VAR } = ${ JSON.stringify({
assets: {
main: cache('main'),
Expand All @@ -222,7 +228,6 @@ export default class ServiceWorker {
},

externals: externals,

hashesMap: hashesMap,

strategy: plugin.strategy,
Expand All @@ -233,13 +238,15 @@ export default class ServiceWorker {
relativePaths: plugin.relativePaths,

prefetchRequest: this.prefetchRequest,

loaders: loaders,
// These aren't added
alwaysRevalidate: plugin.alwaysRevalidate,
preferOnline: plugin.preferOnline,
ignoreSearch: plugin.ignoreSearch,
}, null, minify ? void 0 : ' ') };
`.trim();

return result;
}

getConfig(plugin) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -870,6 +877,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -513,9 +513,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -861,6 +868,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -882,6 +889,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
10 changes: 9 additions & 1 deletion tests/legacy/fixtures/appshell-basic/__expected/webpack2/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -870,6 +877,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
10 changes: 9 additions & 1 deletion tests/legacy/fixtures/appshell-basic/__expected/webpack3/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,9 +513,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -861,6 +868,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
10 changes: 9 additions & 1 deletion tests/legacy/fixtures/appshell-basic/__expected/webpack4/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -882,6 +889,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,16 @@ function WebpackServiceWorker(params, helpers) {
});
}

function shouldServeFromNetwork(response, urlString, cacheUrl) {
if (helpers.shouldServeFromNetwork) {
return helpers.shouldServeFromNetwork(response, urlString, cacheUrl);
}
return response.ok;
}

function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (shouldServeFromNetwork(response, urlString, cacheUrl)) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
Expand Down Expand Up @@ -870,6 +877,7 @@ function logGroup(title, assets) {
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
shouldServeFromNetwork: (void 0),
loaders: {},
cacheMaps: [],
navigationPreload: false,
Expand Down