This is a re-implementation of the 'use cache' directive from Next.js. It is not as feature-complete as the original, but it is a good way to learn about the internals of Next.js.
- Takes the input as such:
async function fetchUserData(userId: string) {
'use cache'; // special directive to turn this function into a cached function
// sets cache lifetime to 10 seconds
cacheLife(10_000);
// sets cache tag to `user:${userId}` to be used for revalidation
cacheTag(`user:${userId}`);
// fetches user data from the database
const userData = await db.users.findUnique({
where: { id: userId },
});
// the returned data is automatically cached
return userData;
}
await fetchUserData('1'); // first call, cache miss
await fetchUserData('1'); // second call, cache hit
await fetchUserData('2'); // different user, cache miss
// for revalidation, you can call:
revalidateTag(`user:${userId}`);
// which deletes the cached data for the given user- Whenever the
fetchUserDatafunction is called, if it has not been cached yet, it will be cached. Otherwise it will return cached data if its cache life has not expired.
This example uses directive-to-hof to transform the 'use cache' directive into a function call. Additionally, it uses AsyncLocalStorage to maintain the cache context for each function call.