cacheData
Caches the result of an async function under a key, for the handler of the current request.
Caches the result of an async function under a key, for the handler of the current request. See the file comment for the rules. During draft mode the function runs every time.
Import#
ts
import { cacheData } from "@shadow-js/dusk/server";
Signature#
ts
async function cacheData<T>(
fn: (signal: AbortSignal) => Promise<T>,
options: CacheDataOptions,
): Promise<T>
Parameters#
| Name | Description |
|---|---|
fn |
The work (a database read, an API call). It receives the signal of the run that concurrent callers share: pass it to fetch or a driver to stop the work when every caller left or the run timed out. |
options |
The key, the tags and the lifetime (revalidate or cacheLife), and the caller's own signal. |
Returns#
The value (cached or fresh).
Throws#
- DuskError
DATA_CACHE_NO_STOREoutside a handler; TypeError for a bad key or lifetime.
Examples#
ts
const post = await cacheData(() => db.post(id), { key: ["post", id], cacheLife: "hours", tags: [`post:${id}`] });