Skip to content

Commit

Permalink
docs: improve cache page
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Mar 7, 2024
1 parent 928373c commit 674089b
Showing 1 changed file with 81 additions and 67 deletions.
148 changes: 81 additions & 67 deletions docs/1.guide/6.cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ icon: ri:speed-line
## Cached event handlers

To cache an event handler, you've just to use the `defineCachedEventHandler` function.
To cache an event handler, you've just to use the `defineCachedEventHandler` method.

It works like the `defineEventHandler` function but with an additional second [options](#options) parameter.
It works like [`defineEventHandler`](https://h3.unjs.io/guide/event-handler) but with an additional second [options](#options) parameter.

```ts [routes/cached.ts]
// Cache an API handler
Expand All @@ -19,7 +19,6 @@ export default defineCachedEventHandler((event) => {
}, { maxAge: 60 * 60 /* 1 hour */ });
```


With this example, the response will be cached for 1 hour and a stale value will be sent to the client while the cache is being updated in the background. If you want to immediately return the updated response set `swr: false`.

::important
Expand All @@ -28,9 +27,13 @@ All incoming request headers are dropped when handling cached responses. If you

See the [options](#options) section for more details about the available options.

::note
You can also use the `cachedEventHandler` method as alias of `defineCachedEventHandler`.
::

## Cached functions

You can also cache a function using the `cachedFunction` function. This is useful to cache the result of a function that is not an event handler but a part of it and reuse it in multiple handlers.
You can also cache a function using the `defineCachedFunction` function. This is useful to cache the result of a function that is not an event handler but a part of it and reuse it in multiple handlers.

For example, you could want to cache for 1 hour the result of an API call:

Expand Down Expand Up @@ -62,6 +65,10 @@ The stars will be cached in development inside **.nitro/cache/functions/ghStars/
{"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}
```

::note
You can also use the `cachedFunction` method as alias of `defineCachedFunction`.
::

## Caching route rules

This feature enables you to add caching routes based on a glob pattern directly in the main configuration file. This is especially useful to have a global cache strategy for a part of your application.
Expand Down Expand Up @@ -180,80 +187,87 @@ export default defineNuxtConfig({
```
::


## Options

The `cachedEventHandler` and `cachedFunction` functions accept the following options:

### `name`

- Type: `String`
- Default: Guessed from function name if not provided and fallback to `_` otherwise.

Handler name.

### `group`

- Type: `String`
- Default: `'nitro/handlers'` for handlers and `'nitro/functions'` for functions.

Part of cache name. Useful to organize cache storage.

### `getKey`

- Type: `Function`
- Default: If not provided, a built-in hash function will be used that will generate a key based on the function arguments.

A function that accepts the same arguments of the function and returns a cache key (`String`).

### `integrity`

- Type: `String`
- Default: Computed from **function code**, used in development to invalidate the cache when the function code changes.

A value that invalidates the cache when changed.

### `maxAge`

- Type: `Number`
- Default: `1` (second).

Maximum age that cache is valid in seconds.

### `staleMaxAge`

- Type: `Number`
- Default: `0` (disabled).

Maximum age that a stale cache is valid in seconds. If set to `-1` a stale value will still be sent to the client, while updating the cache in the background.

### `swr`

- Default: `true`

Enable `stale-while-revalidate` behavior.

### `base`

- Default: `cache`.

Name of the storage mountpoint to use for caching.

### `shouldInvalidateCache`
::field-group
::field{name="base" type="string"}
Name of the storage mountpoint to use for caching, default is `'cache'`.
::
::field{name="name" type="string"}
Guessed from function name if not provided and fallback to `'_'` otherwise.
::
::field{name="group" type="string"}
Default to `'nitro/handlers'` for handlers and `'nitro/functions'` for functions.
::
::field{name="getKey()" type="(...args) => string"}
A function that accepts the same arguments of the function and returns a cache key (`String`). :br
If not provided, a built-in hash function will be used that will generate a key based on the function arguments.
::
::field{name="integrity" type="string"}
By default, it is computed from **function code**, used in development to invalidate the cache when the function code changes.
::
::field{name="integrity" type="string"}
A value that invalidates the cache when changed. :br
By default, it is computed from **function code**, used in development to invalidate the cache when the function code changes.
::
::field{name="maxAge" type="number"}
Maximum age that cache is valid in seconds. :br
Default to `1` (second).
::
::field{name="staleMaxAge" type="number"}
Maximum age that a stale cache is valid in seconds. If set to `-1` a stale value will still be sent to the client, while updating the cache in the background. :br
Default to `0` (disabled).
::
::field{name="swr" type="boolean"}
Enable `stale-while-revalidate` behavior to serve a stale cached response while asynchronously revalidating it. :br
Default to `true`.
::
::field{name="base" type="string"}
Name of the storage mountpoint to use for caching. :br
Default to `cache`.
::
::field{name="shouldInvalidateCache()" type="(..args) => boolean"}
A function that returns a `boolean` to invalidate the current cache and create a new one.
::
::field{name="shouldBypassCache()" type="(..args) => boolean"}
A function that returns a `boolean` to bypass the current cache without invalidating the existing entry.
::
::field{name="varies" type="string[]"}
An array of request headers to be considered for the cache, [learn more](https://github.com/unjs/nitro/issues/1031).
::
::

- Type: `Function`
## Cache keys and invalidation

A function that returns a `Boolean` to invalidate the current cache and create a new one.
When using the `defineCachedFunction` or `defineCachedEventHandler` functions, the cache key is generated using the following pattern:

### `shouldBypassCache`
```ts
`${options.group}:${options.name}:${options.getKey(...args)}.json`
```

- Type: `Function`
For example, the following function:

A function that returns a boolean to bypass the current cache without invalidating the existing entry.
```ts
const getAccessToken = defineCachedFunction(() => {
return String(Date.now())
}, {
maxAge: 10,
name: 'getAccessToken',
getKey: () => 'default'
})
```

### `varies`
Will generate the following cache key:

- Type: `string[]`
```ts
nitro:functions:getAccessToken:default.json
```

An array of request headers to be considered for the cache
You can invalidate the cached function entry with:

```ts
await useStorage('cache').removeItem('nitro:functions:getAccessToken:default.json')
```

0 comments on commit 674089b

Please sign in to comment.