| 1 | /*
|
|---|
| 2 | Copyright 2018 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 |
|
|---|
| 9 | import {WorkboxPlugin} from 'workbox-core/types.js';
|
|---|
| 10 | import {createPartialResponse} from './createPartialResponse.js';
|
|---|
| 11 | import './_version.js';
|
|---|
| 12 |
|
|---|
| 13 | /**
|
|---|
| 14 | * The range request plugin makes it easy for a request with a 'Range' header to
|
|---|
| 15 | * be fulfilled by a cached response.
|
|---|
| 16 | *
|
|---|
| 17 | * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
|
|---|
| 18 | * and returning the appropriate subset of the cached response body.
|
|---|
| 19 | *
|
|---|
| 20 | * @memberof workbox-range-requests
|
|---|
| 21 | */
|
|---|
| 22 | class RangeRequestsPlugin implements WorkboxPlugin {
|
|---|
| 23 | /**
|
|---|
| 24 | * @param {Object} options
|
|---|
| 25 | * @param {Request} options.request The original request, which may or may not
|
|---|
| 26 | * contain a Range: header.
|
|---|
| 27 | * @param {Response} options.cachedResponse The complete cached response.
|
|---|
| 28 | * @return {Promise<Response>} If request contains a 'Range' header, then a
|
|---|
| 29 | * new response with status 206 whose body is a subset of `cachedResponse` is
|
|---|
| 30 | * returned. Otherwise, `cachedResponse` is returned as-is.
|
|---|
| 31 | *
|
|---|
| 32 | * @private
|
|---|
| 33 | */
|
|---|
| 34 | cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({
|
|---|
| 35 | request,
|
|---|
| 36 | cachedResponse,
|
|---|
| 37 | }) => {
|
|---|
| 38 | // Only return a sliced response if there's something valid in the cache,
|
|---|
| 39 | // and there's a Range: header in the request.
|
|---|
| 40 | if (cachedResponse && request.headers.has('range')) {
|
|---|
| 41 | return await createPartialResponse(request, cachedResponse);
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | // If there was no Range: header, or if cachedResponse wasn't valid, just
|
|---|
| 45 | // pass it through as-is.
|
|---|
| 46 | return cachedResponse;
|
|---|
| 47 | };
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | export {RangeRequestsPlugin};
|
|---|