Strategy.ts
9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
Copyright 2020 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {cacheNames} from 'workbox-core/_private/cacheNames.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {logger} from 'workbox-core/_private/logger.js';
import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {
HandlerCallbackOptions,
RouteHandlerObject,
WorkboxPlugin,
} from 'workbox-core/types.js';
import {StrategyHandler} from './StrategyHandler.js';
import './_version.js';
export interface StrategyOptions {
cacheName?: string;
plugins?: WorkboxPlugin[];
fetchOptions?: RequestInit;
matchOptions?: CacheQueryOptions;
}
/**
* An abstract base class that all other strategy classes must extend from:
*
* @memberof workbox-strategies
*/
abstract class Strategy implements RouteHandlerObject {
cacheName: string;
plugins: WorkboxPlugin[];
fetchOptions?: RequestInit;
matchOptions?: CacheQueryOptions;
protected abstract _handle(
request: Request,
handler: StrategyHandler,
): Promise<Response | undefined>;
/**
* Creates a new instance of the strategy and sets all documented option
* properties as public instance properties.
*
* Note: if a custom strategy class extends the base Strategy class and does
* not need more than these properties, it does not need to define its own
* constructor.
*
* @param {Object} [options]
* @param {string} [options.cacheName] Cache name to store and retrieve
* requests. Defaults to the cache names provided by
* {@link workbox-core.cacheNames}.
* @param {Array<Object>} [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)
* of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
* `fetch()` requests made by this strategy.
* @param {Object} [options.matchOptions] The
* [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
* for any `cache.match()` or `cache.put()` calls made by this strategy.
*/
constructor(options: StrategyOptions = {}) {
/**
* Cache name to store and retrieve
* requests. Defaults to the cache names provided by
* {@link workbox-core.cacheNames}.
*
* @type {string}
*/
this.cacheName = cacheNames.getRuntimeName(options.cacheName);
/**
* The list
* [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
* used by this strategy.
*
* @type {Array<Object>}
*/
this.plugins = options.plugins || [];
/**
* Values passed along to the
* [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
* of all fetch() requests made by this strategy.
*
* @type {Object}
*/
this.fetchOptions = options.fetchOptions;
/**
* The
* [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
* for any `cache.match()` or `cache.put()` calls made by this strategy.
*
* @type {Object}
*/
this.matchOptions = options.matchOptions;
}
/**
* Perform a request strategy and returns a `Promise` that will resolve with
* a `Response`, invoking all relevant plugin callbacks.
*
* When a strategy instance is registered with a Workbox
* {@link workbox-routing.Route}, this method is automatically
* called when the route matches.
*
* Alternatively, this method can be used in a standalone `FetchEvent`
* listener by passing it to `event.respondWith()`.
*
* @param {FetchEvent|Object} options A `FetchEvent` or an object with the
* properties listed below.
* @param {Request|string} options.request A request to run this strategy for.
* @param {ExtendableEvent} options.event The event associated with the
* request.
* @param {URL} [options.url]
* @param {*} [options.params]
*/
handle(options: FetchEvent | HandlerCallbackOptions): Promise<Response> {
const [responseDone] = this.handleAll(options);
return responseDone;
}
/**
* Similar to {@link workbox-strategies.Strategy~handle}, but
* instead of just returning a `Promise` that resolves to a `Response` it
* it will return an tuple of `[response, done]` promises, where the former
* (`response`) is equivalent to what `handle()` returns, and the latter is a
* Promise that will resolve once any promises that were added to
* `event.waitUntil()` as part of performing the strategy have completed.
*
* You can await the `done` promise to ensure any extra work performed by
* the strategy (usually caching responses) completes successfully.
*
* @param {FetchEvent|Object} options A `FetchEvent` or an object with the
* properties listed below.
* @param {Request|string} options.request A request to run this strategy for.
* @param {ExtendableEvent} options.event The event associated with the
* request.
* @param {URL} [options.url]
* @param {*} [options.params]
* @return {Array<Promise>} A tuple of [response, done]
* promises that can be used to determine when the response resolves as
* well as when the handler has completed all its work.
*/
handleAll(
options: FetchEvent | HandlerCallbackOptions,
): [Promise<Response>, Promise<void>] {
// Allow for flexible options to be passed.
if (options instanceof FetchEvent) {
options = {
event: options,
request: options.request,
};
}
const event = options.event;
const request =
typeof options.request === 'string'
? new Request(options.request)
: options.request;
const params = 'params' in options ? options.params : undefined;
const handler = new StrategyHandler(this, {event, request, params});
const responseDone = this._getResponse(handler, request, event);
const handlerDone = this._awaitComplete(
responseDone,
handler,
request,
event,
);
// Return an array of promises, suitable for use with Promise.all().
return [responseDone, handlerDone];
}
async _getResponse(
handler: StrategyHandler,
request: Request,
event: ExtendableEvent,
): Promise<Response> {
await handler.runCallbacks('handlerWillStart', {event, request});
let response: Response | undefined = undefined;
try {
response = await this._handle(request, handler);
// The "official" Strategy subclasses all throw this error automatically,
// but in case a third-party Strategy doesn't, ensure that we have a
// consistent failure when there's no response or an error response.
if (!response || response.type === 'error') {
throw new WorkboxError('no-response', {url: request.url});
}
} catch (error) {
if (error instanceof Error) {
for (const callback of handler.iterateCallbacks('handlerDidError')) {
response = await callback({error, event, request});
if (response) {
break;
}
}
}
if (!response) {
throw error;
} else if (process.env.NODE_ENV !== 'production') {
logger.log(
`While responding to '${getFriendlyURL(request.url)}', ` +
`an ${
error instanceof Error ? error.toString() : ''
} error occurred. Using a fallback response provided by ` +
`a handlerDidError plugin.`,
);
}
}
for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
response = await callback({event, request, response});
}
return response;
}
async _awaitComplete(
responseDone: Promise<Response>,
handler: StrategyHandler,
request: Request,
event: ExtendableEvent,
): Promise<void> {
let response;
let error;
try {
response = await responseDone;
} catch (error) {
// Ignore errors, as response errors should be caught via the `response`
// promise above. The `done` promise will only throw for errors in
// promises passed to `handler.waitUntil()`.
}
try {
await handler.runCallbacks('handlerDidRespond', {
event,
request,
response,
});
await handler.doneWaiting();
} catch (waitUntilError) {
if (waitUntilError instanceof Error) {
error = waitUntilError;
}
}
await handler.runCallbacks('handlerDidComplete', {
event,
request,
response,
error: error as Error,
});
handler.destroy();
if (error) {
throw error;
}
}
}
export {Strategy};
/**
* Classes extending the `Strategy` based class should implement this method,
* and leverage the {@link workbox-strategies.StrategyHandler}
* arg to perform all fetching and cache logic, which will ensure all relevant
* cache, cache options, fetch options and plugins are used (per the current
* strategy instance).
*
* @name _handle
* @instance
* @abstract
* @function
* @param {Request} request
* @param {workbox-strategies.StrategyHandler} handler
* @return {Promise<Response>}
*
* @memberof workbox-strategies.Strategy
*/