Skip to content

Commit

Permalink
refactor: types (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
aui authored Apr 19, 2024
1 parent c8aae76 commit c3db08e
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 47 deletions.
5 changes: 5 additions & 0 deletions .changeset/gorgeous-beds-yawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@web-widget/shared-cache": patch
---

Refactor types.
32 changes: 16 additions & 16 deletions src/cache-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export type FilterOptions =
}
| boolean;

export type CacheKeyRules = {
export type SharedCacheKeyRules = {
/** Use cookie as part of cache key. */
cookie?: FilterOptions;
/** Use device type as part of cache key. */
Expand All @@ -32,28 +32,24 @@ export type CacheKeyRules = {
[customPart: string]: FilterOptions | undefined;
};

export type PartDefiner = (
export type SharedCacheKeyPartDefiner = (
request: Request,
options?: FilterOptions
) => Promise<string>;

export type BuiltInExpandedPartDefiner = (
export type SharedCacheKeyPartDefiners = {
[customPart: string]: SharedCacheKeyPartDefiner | undefined;
};

type BuiltInExpandedPartDefiner = (
request: Request,
options?: FilterOptions
) => Promise<string>;

export type CacheKeyPartDefiners = {
[customPart: string]: PartDefiner | undefined;
};

export type BuiltInExpandedCacheKeyPartDefiners = {
type BuiltInExpandedCacheKeyPartDefiners = {
[customPart: string]: BuiltInExpandedPartDefiner | undefined;
};

export async function shortHash(data: Parameters<typeof sha1>[0]) {
return (await sha1(data))?.slice(0, 6);
}

export function filter(
array: [key: string, value: string][],
options?: FilterOptions | boolean
Expand Down Expand Up @@ -84,6 +80,10 @@ export function filter(
return result;
}

async function shortHash(data: Parameters<typeof sha1>[0]) {
return (await sha1(data))?.slice(0, 6);
}

function sort(array: [key: string, value: string][]) {
return array.sort((a, b) => a[0].localeCompare(b[0]));
}
Expand Down Expand Up @@ -229,7 +229,7 @@ const BUILT_IN_EXPANDED_PART_DEFINERS: BuiltInExpandedCacheKeyPartDefiners = {
method,
};

export const DEFAULT_CACHE_KEY_RULES: CacheKeyRules = {
export const DEFAULT_CACHE_KEY_RULES: SharedCacheKeyRules = {
host: true,
method: { include: ['GET', 'HEAD'] },
pathname: true,
Expand All @@ -240,12 +240,12 @@ const CACHE_KEYS = new WeakMap();

export function createCacheKeyGenerator(
cacheName?: string,
cacheKeyPartDefiners?: CacheKeyPartDefiners
cacheKeyPartDefiners?: SharedCacheKeyPartDefiners
) {
return async function cacheKeyGenerator(
request: Request,
options: {
cacheKeyRules?: CacheKeyRules;
cacheKeyRules?: SharedCacheKeyRules;
} & CacheQueryOptions = {}
): Promise<string> {
if (CACHE_KEYS.has(request)) {
Expand All @@ -258,7 +258,7 @@ export function createCacheKeyGenerator(

const { cacheKeyRules = DEFAULT_CACHE_KEY_RULES } = options;
const { host, pathname, search, ...fragmentRules } = cacheKeyRules;
const urlRules: CacheKeyRules = { host, pathname, search };
const urlRules: SharedCacheKeyRules = { host, pathname, search };
const url = new URL(request.url);
const urlPart: string[] = BUILT_IN_URL_PART_KEYS.filter(
(name) => urlRules[name]
Expand Down
2 changes: 1 addition & 1 deletion src/cache-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class SharedCacheStorage implements CacheStorage {
* @param cacheName The name of the cache you want to open.
* @returns A Promise that resolves to the requested Cache object.
*/
async open(cacheName: string): Promise<Cache> {
async open(cacheName: string): Promise<SharedCache> {
const cache = this.#caches.get(cacheName);
if (cache) {
return cache;
Expand Down
10 changes: 5 additions & 5 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import type {
SharedCacheQueryOptions,
CacheItem,
PolicyResponse,
CacheStatus,
SharedCacheStatus,
} from './types';
import { createCacheKeyGenerator, vary as getVary } from './cache-key';
import type { CacheKeyRules, FilterOptions } from './cache-key';
import type { SharedCacheKeyRules, FilterOptions } from './cache-key';
import { CACHE_STATUS_HEADERS_NAME, EXPIRED, HIT, STALE } from './constants';

const ORIGINAL_FETCH = globalThis.fetch;

export class SharedCache implements Cache {
#storage: KVStorage;
#waitUntil: (promise: Promise<any>) => void;
#cacheKeyRules?: CacheKeyRules;
#cacheKeyRules?: SharedCacheKeyRules;
#fetch: typeof fetch;
#cacheKeyGenerator: (
request: Request,
Expand All @@ -25,7 +25,7 @@ export class SharedCache implements Cache {

constructor(storage: KVStorage, options?: SharedCacheOptions) {
if (!storage) {
throw new TypeError('storage is required.');
throw TypeError('Missing storage.');
}

const resolveOptions = {
Expand Down Expand Up @@ -273,7 +273,7 @@ export class SharedCache implements Cache {
});
}

#setCacheStatus(headers: Headers, status: CacheStatus) {
#setCacheStatus(headers: Headers, status: SharedCacheStatus) {
headers.set(CACHE_STATUS_HEADERS_NAME, status);
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { CacheStatus } from './types';
import { SharedCacheStatus } from './types';

export const CACHE_STATUS_HEADERS_NAME = 'x-cache-status';
export const HIT: CacheStatus = 'HIT';
export const MISS: CacheStatus = 'MISS';
export const EXPIRED: CacheStatus = 'EXPIRED';
export const STALE: CacheStatus = 'STALE';
export const BYPASS: CacheStatus = 'BYPASS';
export const REVALIDATED: CacheStatus = 'REVALIDATED';
export const DYNAMIC: CacheStatus = 'DYNAMIC';
export const HIT: SharedCacheStatus = 'HIT';
export const MISS: SharedCacheStatus = 'MISS';
export const EXPIRED: SharedCacheStatus = 'EXPIRED';
export const STALE: SharedCacheStatus = 'STALE';
export const BYPASS: SharedCacheStatus = 'BYPASS';
export const REVALIDATED: SharedCacheStatus = 'REVALIDATED';
export const DYNAMIC: SharedCacheStatus = 'DYNAMIC';
16 changes: 7 additions & 9 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { cacheControl, fresh, vary } from '@web-widget/helpers/headers';
import { cacheControl, vary } from '@web-widget/helpers/headers';
import { SharedCache } from './cache';
import { SharedCacheStorage } from './cache-storage';
import {
Expand All @@ -9,11 +9,10 @@ import {
MISS,
} from './constants';
import {
CacheStatus,
SharedCacheStatus,
SharedCacheFetch,
SharedCacheRequestInitProperties,
} from './types';
import { STATUS_TEXT, Status } from '@web-widget/helpers/status';

const ORIGINAL_FETCH = globalThis.fetch;

Expand All @@ -25,17 +24,16 @@ export function createSharedCacheFetch(
): SharedCacheFetch {
const fetcher = options?.fetch ?? ORIGINAL_FETCH;
return async function fetch(input, init) {
cache ??=
caches instanceof SharedCacheStorage
? ((await caches.open('default')) as SharedCache)
: undefined;
if (!cache && globalThis.caches instanceof SharedCacheStorage) {
cache = await globalThis.caches.open('default');
}

if (!cache) {
throw TypeError('Missing cache.');
}

if (!(cache instanceof SharedCache)) {
throw TypeError('Cache is not an instance of SharedCache.');
throw TypeError('Invalid cache.');
}

const request = new Request(input, init);
Expand Down Expand Up @@ -89,7 +87,7 @@ export function createSharedCacheFetch(

export const sharedCacheFetch = createSharedCacheFetch();

function setCacheStatus(headers: Headers, status: CacheStatus) {
function setCacheStatus(headers: Headers, status: SharedCacheStatus) {
if (!headers.has(CACHE_STATUS_HEADERS_NAME)) {
headers.set(CACHE_STATUS_HEADERS_NAME, status);
}
Expand Down
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ export {
sharedCacheFetch as fetch,
} from './fetch';
export {
SharedCacheOptions as CacheOptions,
SharedCacheQueryOptions as CacheQueryOptions,
KVStorage,
CacheStatus,
SharedCacheFetch as Fetch,
SharedCacheKeyPartDefiners as CacheKeyPartDefiners,
SharedCacheKeyRules as CacheKeyRules,
SharedCacheOptions as CacheOptions,
SharedCacheQueryOptions as CacheQueryOptions,
SharedCacheRequestInitProperties as RequestInitProperties,
SharedCacheStatus as CacheStatus,
} from './types';
12 changes: 7 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import CachePolicy, {
CachePolicyObject,
} from '@web-widget/http-cache-semantics';
import { CacheKeyPartDefiners, CacheKeyRules } from './cache-key';
import { SharedCacheKeyPartDefiners, SharedCacheKeyRules } from './cache-key';

export { SharedCacheKeyRules, SharedCacheKeyPartDefiners };

export type SharedCacheOptions = {
/**
Expand All @@ -13,12 +15,12 @@ export type SharedCacheOptions = {
/**
* Default cache key rules.
*/
cacheKeyRules?: CacheKeyRules;
cacheKeyRules?: SharedCacheKeyRules;

/**
* Define custom parts for cache keys.
*/
cacheKeyPartDefiners?: CacheKeyPartDefiners;
cacheKeyPartDefiners?: SharedCacheKeyPartDefiners;

waitUntil?: (promise: Promise<any>) => void;

Expand Down Expand Up @@ -48,7 +50,7 @@ export type PolicyResponse = {
response: Response;
};

export type CacheStatus =
export type SharedCacheStatus =
| 'HIT'
| 'MISS'
| 'EXPIRED'
Expand All @@ -58,7 +60,7 @@ export type CacheStatus =
| 'DYNAMIC';

export type SharedCacheQueryOptions = {
cacheKeyRules?: CacheKeyRules;
cacheKeyRules?: SharedCacheKeyRules;
/**
* Force cache to be used even if it's stale.
*/
Expand Down

0 comments on commit c3db08e

Please sign in to comment.