Convert workbox-cacheable-response to Typescript (#2093)

* Move and rename files to .ts and update imports

* Add tpe definitions

* Add missed typings in previously converted code
This commit is contained in:
Philip Walton
2019-07-08 09:41:58 -04:00
committed by Jeffrey Posnick
parent 96703319e6
commit c5cab240a0
13 changed files with 97 additions and 57 deletions
+1
View File
@@ -27,5 +27,6 @@ packages/workbox-*/**/*.js
# Individual package ignores during TypeScript migration
packages/workbox-background-sync/**/*.mjs
packages/workbox-broadcast-update/**/*.mjs
packages/workbox-cacheable-response/**/*.mjs
packages/workbox-core/**/*.mjs
packages/workbox-window/**/*.mjs
+13 -19
View File
@@ -7,6 +7,7 @@
*/
import {assert} from 'workbox-core/_private/assert.js';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {BroadcastCacheUpdate, BroadcastCacheUpdateOptions} from './BroadcastCacheUpdate.js';
import './_version.js';
@@ -16,7 +17,7 @@ import './_version.js';
*
* @memberof workbox.broadcastUpdate
*/
class Plugin {
class Plugin implements WorkboxPlugin {
private _broadcastUpdate: BroadcastCacheUpdate;
/**
@@ -53,19 +54,13 @@ class Plugin {
* @param {Request} options.request The request that triggered the udpate.
* @param {Request} [options.event] The event that triggered the update.
*/
cacheDidUpdate({
cacheDidUpdate: WorkboxPlugin['cacheDidUpdate'] = async ({
cacheName,
oldResponse,
newResponse,
request,
event
}: {
cacheName: string,
oldResponse?: Response,
newResponse: Response,
request: Request,
event?: FetchEvent
}) {
}) => {
if (process.env.NODE_ENV !== 'production') {
assert!.isType(cacheName, 'string', {
moduleName: 'workbox-broadcast-update',
@@ -87,17 +82,16 @@ class Plugin {
});
}
if (!oldResponse) {
// Without a two responses there is nothing to compare.
return;
// Without a two responses there is nothing to compare.
if (oldResponse) {
this._broadcastUpdate.notifyIfUpdated({
cacheName,
oldResponse,
newResponse,
event,
url: request.url,
});
}
this._broadcastUpdate.notifyIfUpdated({
cacheName,
oldResponse,
newResponse,
event,
url: request.url,
});
}
}
@@ -1 +0,0 @@
try{self['workbox:cacheable-response:4.3.1']&&_()}catch(e){}// eslint-disable-line
@@ -23,8 +23,9 @@
"browserNamespace": "workbox.cacheableResponse",
"packageType": "browser"
},
"main": "build/workbox-cacheable-response.prod.js",
"main": "index.js",
"module": "index.mjs",
"types": "index.d.ts",
"dependencies": {
"workbox-core": "^4.3.1"
}
@@ -6,11 +6,17 @@
https://opensource.org/licenses/MIT.
*/
import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
import {assert} from 'workbox-core/_private/assert.mjs';
import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';
import {logger} from 'workbox-core/_private/logger.mjs';
import './_version.mjs';
import {assert} from 'workbox-core/_private/assert.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {logger} from 'workbox-core/_private/logger.js';
import './_version.js';
export interface CacheableResponseOptions {
statuses?: number[];
headers?: {[headerName: string]: string};
}
/**
* This class allows you to set up rules determining what
@@ -21,6 +27,9 @@ import './_version.mjs';
* @memberof workbox.cacheableResponse
*/
class CacheableResponse {
private _statuses?: CacheableResponseOptions['statuses'];
private _headers?: CacheableResponseOptions['headers'];
/**
* To construct a new CacheableResponse instance you must provide at least
* one of the `config` properties.
@@ -35,7 +44,7 @@ class CacheableResponse {
* and expected values that a `Response` can have and be considered cacheable.
* If multiple headers are provided, only one needs to be present.
*/
constructor(config = {}) {
constructor(config: CacheableResponseOptions = {}) {
if (process.env.NODE_ENV !== 'production') {
if (!(config.statuses || config.headers)) {
throw new WorkboxError('statuses-or-headers-required', {
@@ -46,7 +55,7 @@ class CacheableResponse {
}
if (config.statuses) {
assert.isArray(config.statuses, {
assert!.isArray(config.statuses, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
@@ -55,7 +64,7 @@ class CacheableResponse {
}
if (config.headers) {
assert.isType(config.headers, 'object', {
assert!.isType(config.headers, 'object', {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
@@ -77,9 +86,9 @@ class CacheableResponse {
* @return {boolean} `true` if the `Response` is cacheable, and `false`
* otherwise.
*/
isResponseCacheable(response) {
isResponseCacheable(response: Response): boolean {
if (process.env.NODE_ENV !== 'production') {
assert.isInstance(response, Response, {
assert!.isInstance(response, Response, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'isResponseCacheable',
@@ -95,7 +104,7 @@ class CacheableResponse {
if (this._headers && cacheable) {
cacheable = Object.keys(this._headers).some((headerName) => {
return response.headers.get(headerName) === this._headers[headerName];
return response.headers.get(headerName) === this._headers![headerName];
});
}
@@ -112,7 +121,7 @@ class CacheableResponse {
JSON.stringify(this._headers, null, 2));
logger.groupEnd();
const logFriendlyHeaders = {};
const logFriendlyHeaders: {[key: string]: string} = {};
response.headers.forEach((value, key) => {
logFriendlyHeaders[key] = value;
});
@@ -6,8 +6,9 @@
https://opensource.org/licenses/MIT.
*/
import {CacheableResponse} from './CacheableResponse.mjs';
import './_version.mjs';
import {WorkboxPlugin} from 'workbox-core/utils/pluginUtils.js';
import {CacheableResponse, CacheableResponseOptions} from './CacheableResponse.js';
import './_version.js';
/**
* A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
@@ -16,7 +17,9 @@ import './_version.mjs';
*
* @memberof workbox.cacheableResponse
*/
class Plugin {
class Plugin implements WorkboxPlugin {
private _cacheableResponse: CacheableResponse;
/**
* To construct a new cacheable response Plugin instance you must provide at
* least one of the `config` properties.
@@ -31,17 +34,17 @@ class Plugin {
* and expected values that a `Response` can have and be considered cacheable.
* If multiple headers are provided, only one needs to be present.
*/
constructor(config) {
constructor(config: CacheableResponseOptions) {
this._cacheableResponse = new CacheableResponse(config);
}
/**
* @param {Object} options
* @param {Response} options.response
* @return {boolean}
* @return {Response|null}
* @private
*/
cacheWillUpdate({response}) {
cacheWillUpdate: WorkboxPlugin['cacheWillUpdate'] = async ({response}) => {
if (this._cacheableResponse.isResponseCacheable(response)) {
return response;
}
@@ -0,0 +1,2 @@
// @ts-ignore
try{self['workbox:cacheable-response:4.3.1']&&_()}catch(e){}
@@ -6,9 +6,9 @@
https://opensource.org/licenses/MIT.
*/
import {CacheableResponse} from './CacheableResponse.mjs';
import {Plugin} from './Plugin.mjs';
import './_version.mjs';
import {CacheableResponse} from './CacheableResponse.js';
import {Plugin} from './Plugin.js';
import './_version.js';
/**
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "./",
"rootDir": "./src"
},
"include": [
"src/**/*.ts"
]
}
+23 -3
View File
@@ -9,11 +9,31 @@
import '../_version.js';
export interface WorkboxPlugin {
cacheDidUpdate?: Function;
cacheDidUpdate?: ({
cacheName,
oldResponse,
newResponse,
request,
event
}: {
cacheName: string,
oldResponse?: Response,
newResponse: Response,
request: Request,
event?: FetchEvent
}) => Promise<void>;
cacheKeyWillBeUsed?: Function;
cacheWillUpdate?: Function;
cacheWillUpdate?: ({
response
}: {
response: Response
}) => Promise<Response | null>;
cachedResponseWillBeUsed?: Function;
fetchDidFail?: ({request}: {request: Request}) => Promise<void>;
fetchDidFail?: ({
request
}: {
request: Request
}) => Promise<void>;
fetchDidSucceed?: Function;
requestWillFetch?: Function;
}
@@ -24,26 +24,26 @@ describe(`Plugin`, function() {
it(`should throw when called and cacheName is missing`, function() {
if (process.env.NODE_ENV === 'production') this.skip();
return expectError(() => {
return expectError(async () => {
const bcuPlugin = new Plugin();
const oldResponse = new Response();
const newResponse = new Response();
bcuPlugin.cacheDidUpdate({oldResponse, newResponse});
await bcuPlugin.cacheDidUpdate({oldResponse, newResponse});
}, 'incorrect-type');
});
it(`should throw when called and newResponse is missing`, function() {
if (process.env.NODE_ENV === 'production') this.skip();
return expectError(() => {
return expectError(async () => {
const bcuPlugin = new Plugin();
const cacheName = 'cache-name';
const oldResponse = new Response();
bcuPlugin.cacheDidUpdate({cacheName, oldResponse});
await bcuPlugin.cacheDidUpdate({cacheName, oldResponse});
}, 'incorrect-class');
});
it(`should not throw when called with valid parameters`, function() {
it(`should not throw when called with valid parameters`, async function() {
const bcuPlugin = new Plugin();
sandbox.spy(bcuPlugin._broadcastUpdate, 'notifyIfUpdated');
@@ -51,12 +51,12 @@ describe(`Plugin`, function() {
const request = new Request('/');
const oldResponse = new Response();
const newResponse = new Response();
bcuPlugin.cacheDidUpdate({cacheName, oldResponse, newResponse, request});
await bcuPlugin.cacheDidUpdate({cacheName, oldResponse, newResponse, request});
expect(bcuPlugin._broadcastUpdate.notifyIfUpdated.callCount).to.equal(1);
});
it(`should notify and pass all options`, function() {
it(`should notify and pass all options`, async function() {
const bcuPlugin = new Plugin();
sandbox.spy(bcuPlugin._broadcastUpdate, 'notifyIfUpdated');
@@ -66,7 +66,7 @@ describe(`Plugin`, function() {
const oldResponse = new Response();
const event = new FetchEvent('fetch', {request});
bcuPlugin.cacheDidUpdate({
await bcuPlugin.cacheDidUpdate({
cacheName,
newResponse,
oldResponse,
@@ -84,14 +84,14 @@ describe(`Plugin`, function() {
});
});
it(`should not notify when no oldResponse supplied`, function() {
it(`should not notify when no oldResponse supplied`, async function() {
const bcuPlugin = new Plugin();
sandbox.spy(bcuPlugin._broadcastUpdate, 'notifyIfUpdated');
const cacheName = 'cache-name';
const request = new Request('/');
const newResponse = new Response();
bcuPlugin.cacheDidUpdate({cacheName, newResponse, request});
await bcuPlugin.cacheDidUpdate({cacheName, newResponse, request});
expect(bcuPlugin._broadcastUpdate.notifyIfUpdated.callCount).to.equal(0);
});
@@ -42,10 +42,10 @@ describe(`Plugin`, function() {
});
describe(`cacheWillUpdate`, function() {
it(`should return null for non-cachable response`, function() {
it(`should return null for non-cachable response`, async function() {
const cacheableResponsePlugin = new Plugin({statuses: STATUSES});
sandbox.stub(cacheableResponsePlugin._cacheableResponse, 'isResponseCacheable').callsFake(() => false);
expect(cacheableResponsePlugin.cacheWillUpdate({
expect(await cacheableResponsePlugin.cacheWillUpdate({
response: new Response(),
})).to.equal(null);
});
+1
View File
@@ -22,6 +22,7 @@
"references": [
{ "path": "./packages/workbox-broadcast-update/" },
{ "path": "./packages/workbox-background-sync/" },
{ "path": "./packages/workbox-cacheable-response/" },
{ "path": "./packages/workbox-core/" },
{ "path": "./packages/workbox-window/" }
]