@fortedigital/nextjs-cache-handler
Version:
Next.js cache handlers
160 lines (157 loc) • 6.01 kB
TypeScript
import { Revalidate } from '../handlers/cache-handler.types.js';
import { IncrementalCache } from 'next/dist/server/lib/incremental-cache';
import 'next/dist/server/lib/incremental-cache/file-system-cache';
declare global {
var __incrementalCache: IncrementalCache | undefined;
}
/**
* @template Arguments - The type of the arguments passed to the callback function.
*
* @template Result - The type of the value returned by the callback function.
*/
type Callback<Arguments extends unknown[], Result> = (...args: Arguments) => Result;
/**
* An object containing options for the cache.
*/
type NeshClassicCacheOptions<Arguments extends unknown[], Result> = {
/**
* The response context object.
* It is used to set the cache headers.
*/
responseContext?: object & {
setHeader(name: string, value: number | string | readonly string[]): unknown;
};
/**
* An array of tags to associate with the cached result.
* Tags are used to revalidate the cache using the `revalidateTag` function.
*/
tags?: string[];
/**
* The revalidation interval in seconds.
* Must be a positive integer or `false` to disable revalidation.
*
* @default revalidate // of the current route
*/
revalidate?: Revalidate;
/**
* A custom cache key to be used instead of creating one from the arguments.
*/
cacheKey?: string;
/**
* A function that serializes the arguments passed to the callback function.
* Use it to create a cache key.
*
* @default (args) => JSON.stringify(args)
*
* @param callbackArguments - The arguments passed to the callback function.
*/
argumentsSerializer?(callbackArguments: Arguments): string;
/**
*
* A function that serializes the result of the callback function.
*
* @default (result) => Buffer.from(JSON.stringify(result)).toString('base64')
*
* @param result - The result of the callback function.
*/
resultSerializer?(result: Result): string;
/**
* A function that deserializes the string representation of the result of the callback function.
*
* @default (string) => JSON.parse(Buffer.from(string, 'base64').toString('utf-8'))
*
* @param string - The string representation of the result of the callback function.
*/
resultDeserializer?(string: string): Result;
};
/**
* An object containing common options for the cache.
*/
type CommonNeshClassicCacheOptions<Arguments extends unknown[], Result> = Omit<NeshClassicCacheOptions<Arguments, Result>, "cacheKey" | "responseContext">;
/**
* Experimental implementation of the "`unstable_cache`" for classic Next.js Pages Router.
* It allows to cache data in the `getServerSideProps` and API routes.
*
* The API may change in the future. Use with caution.
*
* Caches the result of a callback function and returns a cached version if available.
* If not available, it executes the callback function, caches the result, and returns it.
*
* @param callback - The callback function to be cached.
*
* @param options - An object containing options for the cache.
*
* @param options.responseContext - The response context object.
* It is used to set the cache headers.
*
* @param options.tags - An array of tags to associate with the cached result.
* Tags are used to revalidate the cache using the `revalidateTag` function.
*
* @param options.revalidate - The revalidation interval in seconds.
* Must be a positive integer or `false` to disable revalidation.
* Defaults to `export const revalidate = time;` in the current route.
*
* @param options.argumentsSerializer - A function that serializes the arguments passed to the callback function.
* Use it to create a cache key. Defaults to `JSON.stringify(args)`.
*
* @param options.resultSerializer - A function that serializes the result of the callback function.
* Defaults to `Buffer.from(JSON.stringify(data)).toString('base64')`.
*
* @param options.resultDeserializer - A function that deserializes the string representation of the result of the callback function.
* Defaults to `JSON.parse(Buffer.from(data, 'base64').toString('utf-8'))`.
*
* @returns The callback wrapped in a caching function.
* First argument is the cache options which can be used to override the common options.
* In addition, there is a `cacheKey` option that can be used to provide a custom cache key.
*
* @throws If the `neshClassicCache` function is not used in a Next.js Pages directory or if the `revalidate` option is invalid.
*
* @example file: `src/pages/api/api-example.js`
*
* ```js
* import { neshClassicCache } from '@neshca/cache-handler/functions';
* import axios from 'axios';
*
* export const config = {
* runtime: 'nodejs',
* };
*
* async function getViaAxios(url) {
* try {
* return (await axios.get(url.href)).data;
* } catch (_error) {
* return null;
* }
* }
*
* const cachedAxios = neshClassicCache(getViaAxios);
*
* export default async function handler(request, response) {
* if (request.method !== 'GET') {
* return response.status(405).send(null);
* }
*
* const revalidate = 5;
*
* const url = new URL('https://api.example.com/data.json');
*
* // Add tags to be able to revalidate the cache
* const data = await cachedAxios({ revalidate, tags: [url.pathname], responseContext: response }, url);
*
* if (!data) {
* response.status(404).send('Not found');
*
* return;
* }
*
* response.json(data);
* }
* ```
*
* @remarks
* - This function is intended to be used in a Next.js Pages directory.
*
* @since 1.8.0
*/
declare function neshClassicCache<Arguments extends unknown[], Result extends Promise<unknown>>(callback: Callback<Arguments, Result>, commonOptions?: CommonNeshClassicCacheOptions<Arguments, Result>): (options: NeshClassicCacheOptions<Arguments, Result>, ...args: Arguments) => Promise<Result | null>;
export { neshClassicCache };