From dc83a2e20bc778755c19e3085045818a44d99e23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Thu, 21 Mar 2024 12:49:26 +0100 Subject: [PATCH] docs(cache): add a note for serverless environment --- docs/1.guide/6.cache.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/1.guide/6.cache.md b/docs/1.guide/6.cache.md index a6f44743d2..cdbbd6fecc 100644 --- a/docs/1.guide/6.cache.md +++ b/docs/1.guide/6.cache.md @@ -69,6 +69,38 @@ The stars will be cached in development inside **.nitro/cache/functions/ghStars/ You can also use the `cachedFunction` method as alias of `defineCachedFunction`. :: +### Serverless environment + +In a serverless environment, the instance is destroyed after each request. Nitro uses `event.waitUntil` to keep the instance alive while the cache is being updated while the response is sent to the client. + +To make sure your cached functions are working as expected in a serverless environment, you should always give the `event` as first argument to the function. + +::code-group +```ts [utils/github.ts] +import type { H3Event } from 'h3' + +export const cachedGHStars = defineCachedFunction(async (event: H3Event, repo: string) => { + const data: any = await $fetch(`https://api.github.com/repos/${repo}`) + + return data.stargazers_count +}, { + maxAge: 60 * 60, + name: 'ghStars', + getKey: (event: H3Event, repo: string) => repo +}) +``` +```ts [api/stars/[...repo\\].ts] +export default defineEventHandler(async (event) => { + const repo = event.context.params.repo + const stars = await cachedGHStars(event, repo).catch(() => 0) + + return { repo, stars } +}) +``` +:: + +This way, the function will be able to keep the instance alive while the cache is being updated without slowing down the response to the client. + ## 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. @@ -191,7 +223,6 @@ export default defineNuxtConfig({ The `cachedEventHandler` and `cachedFunction` functions accept the following options: - ::field-group ::field{name="base" type="string"} Name of the storage mountpoint to use for caching, default is `'cache'`.