| 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 | import { createPartialResponse } from './createPartialResponse.js';
|
|---|
| 9 | import './_version.js';
|
|---|
| 10 | /**
|
|---|
| 11 | * The range request plugin makes it easy for a request with a 'Range' header to
|
|---|
| 12 | * be fulfilled by a cached response.
|
|---|
| 13 | *
|
|---|
| 14 | * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
|
|---|
| 15 | * and returning the appropriate subset of the cached response body.
|
|---|
| 16 | *
|
|---|
| 17 | * @memberof workbox-range-requests
|
|---|
| 18 | */
|
|---|
| 19 | class RangeRequestsPlugin {
|
|---|
| 20 | constructor() {
|
|---|
| 21 | /**
|
|---|
| 22 | * @param {Object} options
|
|---|
| 23 | * @param {Request} options.request The original request, which may or may not
|
|---|
| 24 | * contain a Range: header.
|
|---|
| 25 | * @param {Response} options.cachedResponse The complete cached response.
|
|---|
| 26 | * @return {Promise<Response>} If request contains a 'Range' header, then a
|
|---|
| 27 | * new response with status 206 whose body is a subset of `cachedResponse` is
|
|---|
| 28 | * returned. Otherwise, `cachedResponse` is returned as-is.
|
|---|
| 29 | *
|
|---|
| 30 | * @private
|
|---|
| 31 | */
|
|---|
| 32 | this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => {
|
|---|
| 33 | // Only return a sliced response if there's something valid in the cache,
|
|---|
| 34 | // and there's a Range: header in the request.
|
|---|
| 35 | if (cachedResponse && request.headers.has('range')) {
|
|---|
| 36 | return await createPartialResponse(request, cachedResponse);
|
|---|
| 37 | }
|
|---|
| 38 | // If there was no Range: header, or if cachedResponse wasn't valid, just
|
|---|
| 39 | // pass it through as-is.
|
|---|
| 40 | return cachedResponse;
|
|---|
| 41 | };
|
|---|
| 42 | }
|
|---|
| 43 | }
|
|---|
| 44 | export { RangeRequestsPlugin };
|
|---|