Skip to content
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,15 @@ The name of the query parameter to be used for skipping the cache copy in an int

##### cache

Type: `boolean`<br/>
Type: `Keyv` instance \| options<br/>
Default: `new Keyv({ namespace: 'ssr' })`

The cache instance used for backed your pre-calculated server side response copies.
The cache backing your pre-calculated server side response copies.

The library delegates in [keyv](https://keyvhq.js.org/), a tiny key value store with [multi adapter support](https://keyvhq.js.org/#/?id=storage-adapters).

Pass a [`@keyvhq/core`](https://keyvhq.js.org/) instance, or the options to create one. A plain `{ get, set }` object is not a cache: it is read as Keyv options, so it is never read from.

If you don't specify it, a memory cache will be used.

##### compress
Expand Down
53 changes: 31 additions & 22 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { IncomingMessage, ServerResponse } from "http";
import Keyv = require("@keyvhq/core");

/**
* Cacheable response is a HTTP middleware for serving a pre-calculated response.
Expand Down Expand Up @@ -61,11 +62,12 @@ declare namespace CacheableResponse {
bypassQueryParameter?: string

/**
* The cache instance used for backed your pre-calculated server side response copies.
* The cache backing your pre-calculated server side response copies:
* a `@keyvhq/core` instance, or the options to create one.
*
* The default value is an in-memory instance.
* The default value is `new Keyv({ namespace: 'ssr' })`, an in-memory instance.
*/
cache?: CacheProvider<GetReturnProps, Data>;
cache?: CacheProvider;

/**
* Enable compress/decompress data using brotli compression format.
Expand Down Expand Up @@ -99,9 +101,12 @@ declare namespace CacheableResponse {

/**
* The method used to determinate how the content should be rendered.
*
* Props are checked here but not inferred from here, so a `Keyv<any>` cache
* cannot widen them. The indexed access is `NoInfer` for TypeScript before 5.4.
*/
send: (
opts: GetReturnProps & { data: Data } & Pick<Options, "req" | "res">
opts: [GetReturnProps][GetReturnProps extends any ? 0 : never] & { data: Data } & Pick<Options, "req" | "res">
) => any;

/**
Expand Down Expand Up @@ -146,24 +151,28 @@ declare namespace CacheableResponse {
staleTtl: number | boolean;
}

export interface CacheProvider<P extends Props, V = any> {
/**
* Returns the cached value.
* With `compress` enabled this is a `CompressedEntry`, or a `Buffer` for older entries.
*/
get(
key: string
): Promise<Buffer | CompressedEntry | (Cache<V> & P) | undefined>;

/**
* Set a value. You can implements an expiry TTL in milliseconds.
*/
set(
key: string,
value: Buffer | CompressedEntry | (Cache<V> & P),
ttl: number
): Promise<true>;
}
/**
* A `@keyvhq/core` instance is used as is.
* Anything else is passed to `new Keyv()` as its options, and its keys are copied onto the instance,
* so an object with its own `get`, `set`, `has`, `delete`, `clear`, `iterator`,
* `_getKeyPrefix`, or `_getKeyUnprefix` would replace those methods instead of being a cache.
* `_getKeyPrefix` is how a read finds the stored entry.
* `serialize`, `deserialize`, and `ttl` are real Keyv options, so they stay allowed.
* `constructor` is on every object, so excluding it would reject real options too.
*/
export type CacheProvider =
| Keyv<any>
| (Keyv.Options<any> & {
[Method in
| "get"
| "set"
| "has"
| "delete"
| "clear"
| "iterator"
| "_getKeyPrefix"
| "_getKeyUnprefix"]?: never;
});

interface Props {
[key: string]: any;
Expand Down
86 changes: 83 additions & 3 deletions test/types.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import cacheableResponse from '../index.js'
import Keyv from '@keyvhq/core'
import type {
CacheProvider,
CompressedEntry,
Expand All @@ -12,9 +13,7 @@ import { createServer } from 'node:http'

type Data = { html: string }

type Provider = CacheProvider<{}, Data>
type StoredValue = Awaited<ReturnType<Provider['get']>>
const entry: StoredValue = { compressed: Buffer.from(''), ttl: 60_000, staleTtl: false } satisfies CompressedEntry
const entry: CompressedEntry = { compressed: Buffer.from(''), ttl: 60_000, staleTtl: false }

const params: InputParams<GetOpts, {}, Data> = {
compress: true,
Expand Down Expand Up @@ -50,3 +49,84 @@ console.log(entry)

// @ts-expect-error module.exports is the function itself, it has no `default` property
console.log(cacheableResponse.default)

const keyvCache = new Keyv({ namespace: 'ssr' })
const keyvOptions: CacheProvider = { namespace: 'ssr', store: new Map() }
const keyvOptionHooks: CacheProvider = {
namespace: 'ssr',
store: new Map(),
ttl: 60_000,
serialize: data => JSON.stringify(data),
deserialize: text => JSON.parse(text)
}
cacheableResponse({ ...params, cache: keyvCache })
cacheableResponse({ ...params, cache: keyvOptions })
cacheableResponse({ ...params, cache: keyvOptionHooks })
// Object.assign copies these keys onto the instance. They are not Keyv methods.
const copiedHooks = {
__defineGetter__: () => undefined,
__defineSetter__: () => undefined,
__lookupGetter__: () => undefined,
__lookupSetter__: () => undefined,
['__proto__']: () => undefined
}
cacheableResponse({ ...params, cache: { namespace: 'ssr', store: new Map(), ...copiedHooks } })
const copiedIterator = { [Symbol.iterator]: () => undefined }
cacheableResponse({ ...params, cache: { namespace: 'ssr', store: new Map(), ...copiedIterator } })
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: keyvCache })

const plainCache = {
get: async (key: string) => undefined,
set: async (key: string, value: unknown, ttl: number) => true
}
// @ts-expect-error a plain `{ get, set }` object is passed to `new Keyv()` as options and never read from
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: plainCache })

const sharedKeyv = new Keyv({ namespace: 'ssr' })
cacheableResponse({
cache: sharedKeyv,
get: async () => ({ data: { html: '<p/>' } }),
// @ts-expect-error `data` is still inferred from `get` when `cache` is a `Keyv<any>`
send: ({ data, res }) => res.end(data.htmll)
})
cacheableResponse({
cache: sharedKeyv,
get: async () => ({ data: { html: '<p/>' }, statusCode: 201 }),
send: ({ data, statusCode, res }) => {
res.statusCode = statusCode
res.end(data.html)
}
})

const adapterKeyv = new Keyv<undefined>({ namespace: 'ssr' })
cacheableResponse({ ...params, cache: adapterKeyv })

// @ts-expect-error `get` and `set` would replace Keyv methods, the object is still never read from
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { ttl: 60_000, ...plainCache } })

// Spread a real Keyv option in with one method. A fresh literal would still
// fail excess-property checks after that method was dropped from the type.
const onlyGet = { get: async (key: string) => undefined }
const onlySet = { set: async (key: string, value: unknown, ttl: number) => true }
const onlyHas = { has: async (key: string) => false }
const onlyDelete = { delete: async (key: string) => false }
const onlyClear = { clear: async () => undefined }
// @ts-expect-error own get replaces Keyv#get
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyGet } })
// @ts-expect-error own set replaces Keyv#set
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlySet } })
// @ts-expect-error own has replaces Keyv#has
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyHas } })
// @ts-expect-error own delete replaces Keyv#delete
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyDelete } })
// @ts-expect-error own clear replaces Keyv#clear
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyClear } })
const onlyPrefix = { _getKeyPrefix: (key: string) => key }
const onlyUnprefix = { _getKeyUnprefix: (key: string) => key }
// @ts-expect-error own _getKeyPrefix replaces the method a read uses to find the entry
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyPrefix } })
// @ts-expect-error own _getKeyUnprefix replaces Keyv's prefix helper
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyUnprefix } })
const onlyIterator = { iterator: () => undefined }
// @ts-expect-error own iterator stays on the instance when the store does not install one
cacheableResponse<GetOpts, {}, Data>({ ...params, cache: { namespace: 'ssr', ...onlyIterator } })
Loading