Skip to content

Commit 056d743

Browse files
committed
Refactoring and cleanup
1 parent 60bb9eb commit 056d743

File tree

9 files changed

+140
-361
lines changed

9 files changed

+140
-361
lines changed

packages/nextjs-cache-handler/src/handlers/cache-handler.ts

Lines changed: 3 additions & 220 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import {
1010
CacheHandlerParametersRevalidateTag,
1111
CacheHandlerParametersSet,
1212
CacheHandlerParametersGet,
13+
Handler,
14+
OnCreationHook,
15+
Revalidate,
1316
} from "./cache-handler.types";
1417
import { PrerenderManifest } from "next/dist/build";
1518
import type {
@@ -19,228 +22,8 @@ import type {
1922
GetIncrementalFetchCacheContext,
2023
} from "next/dist/server/response-cache/types";
2124

22-
export type Revalidate = false | number;
2325
const PRERENDER_MANIFEST_VERSION = 4;
2426

25-
/**
26-
* Represents an internal Next.js metadata for a `get` method.
27-
* This metadata is available in the `get` method of the cache handler.
28-
*/
29-
type HandlerGetMeta = {
30-
/**
31-
* An array of tags that are implicitly associated with the cache entry.
32-
*/
33-
implicitTags: string[];
34-
};
35-
36-
/**
37-
* Represents a cache Handler.
38-
*/
39-
export type Handler = {
40-
/**
41-
* A descriptive name for the cache Handler.
42-
*/
43-
name: string;
44-
/**
45-
* Retrieves the value associated with the given key from the cache.
46-
*
47-
* @param key - The unique string identifier for the cache entry.
48-
*
49-
* @param meta - The metadata object for the `get` method. See {@link HandlerGetMeta}.
50-
*
51-
* @returns A Promise that resolves to the cached value (if found), `null` or `undefined` if the entry is not found.
52-
*
53-
* @example
54-
* ### With auto expiration
55-
*
56-
* If your cache store supports time based key eviction, the `get` method is straightforward.
57-
*
58-
* ```js
59-
* const handler = {
60-
* async get(key) {
61-
* const cacheValue = await cacheStore.get(key);
62-
*
63-
* if (!cacheValue) {
64-
* return null;
65-
* }
66-
*
67-
* return cacheValue;
68-
* }
69-
* }
70-
* ```
71-
*
72-
* ### Without auto expiration
73-
*
74-
* If your cache store does not support time based key eviction,
75-
* you can implement the `delete` method to remove the cache entry when it becomes expired.
76-
*
77-
* ```js
78-
* const handler = {
79-
* async get(key) {
80-
* const cacheValue = await cacheStore.get(key);
81-
*
82-
* if (!cacheValue) {
83-
* return null;
84-
* }
85-
*
86-
* return cacheValue;
87-
* },
88-
* async delete(key) {
89-
* await cacheStore.delete(key);
90-
* }
91-
* }
92-
* ```
93-
*
94-
95-
*/
96-
get: (
97-
key: string,
98-
meta: HandlerGetMeta,
99-
) => Promise<CacheHandlerValue | null | undefined>;
100-
/**
101-
* Sets or updates a value in the cache store.
102-
*
103-
* @param key - The unique string identifier for the cache entry.
104-
*
105-
* @param value - The value to be stored in the cache. See {@link CacheHandlerValue}.
106-
*
107-
* @returns A Promise that resolves when the value has been successfully set in the cache.
108-
*
109-
* @remarks
110-
*
111-
* Read more about the `lifespan` parameter: {@link LifespanParameters}.
112-
*
113-
* ### LifespanParameters
114-
* If no `revalidate` option or `revalidate: false` is set in your [`getStaticProps` ↗](https://nextjs.org/docs/pages/api-reference/functions/get-static-props#revalidate)
115-
* the `lifespan` parameter will be `null` and you should consider the cache entry as always fresh and never stale.
116-
*
117-
* Use the absolute time (`expireAt`) to set and expiration time for the cache entry in your cache store to be in sync with the file system cache.
118-
*
119-
120-
*/
121-
set: (key: string, value: CacheHandlerValue) => Promise<void>;
122-
/**
123-
* Deletes all cache entries that are associated with the specified tag.
124-
* See [fetch `options.next.tags` and `revalidateTag` ↗](https://nextjs.org/docs/app/building-your-application/caching#fetch-optionsnexttags-and-revalidatetag)
125-
*
126-
* @param tag - A string representing the cache tag associated with the data you want to revalidate.
127-
* Must be less than or equal to 256 characters. This value is case-sensitive.
128-
*
129-
130-
*/
131-
revalidateTag: (tag: string) => Promise<void>;
132-
/**
133-
* Deletes the cache entry associated with the given key from the cache store.
134-
* This method is optional and supposed to be used only when the cache store does not support time based key eviction.
135-
* This method will be automatically called by the `CacheHandler` class when the retrieved cache entry is stale.
136-
*
137-
* @param key - The unique string identifier for the cache entry with prefix if present.
138-
*
139-
* @returns A Promise that resolves when the cache entry has been successfully deleted.
140-
*/
141-
delete?: (key: string) => Promise<void>;
142-
};
143-
144-
/**
145-
* Represents the parameters for Time-to-Live (TTL) configuration.
146-
*/
147-
export type TTLParameters = {
148-
/**
149-
* The time in seconds for when the cache entry becomes stale.
150-
*
151-
* @default 31536000 // 1 year
152-
*/
153-
defaultStaleAge: number;
154-
/**
155-
* Estimates the expiration age based on the stale age.
156-
*
157-
* @param staleAge - The stale age in seconds.
158-
* After the stale age, the cache entry is considered stale, can be served from the cache, and should be revalidated.
159-
* Revalidation is handled by the `CacheHandler` class.
160-
*
161-
* @default (staleAge) => staleAge * 1.5
162-
*
163-
* @returns The expiration age in seconds.
164-
*/
165-
estimateExpireAge(staleAge: number): number;
166-
};
167-
168-
/**
169-
* Configuration options for the {@link CacheHandler}.
170-
*/
171-
export type CacheHandlerConfig = {
172-
/**
173-
* An array of cache instances that conform to the Handler interface.
174-
* Multiple caches can be used to implement various caching strategies or layers.
175-
*/
176-
handlers: (Handler | undefined | null)[];
177-
/**
178-
* Time-to-live (TTL) options for the cache entries.
179-
*/
180-
ttl?: Partial<TTLParameters>;
181-
};
182-
183-
/**
184-
* Contextual information provided during cache creation, including server directory paths and environment mode.
185-
*/
186-
export type CacheCreationContext = {
187-
/**
188-
* The absolute path to the Next.js server directory.
189-
*/
190-
serverDistDir: string;
191-
/**
192-
* Indicates if the Next.js application is running in development mode.
193-
* When in development mode, caching behavior might differ.
194-
*/
195-
dev?: boolean;
196-
/**
197-
* The unique identifier for the current build of the Next.js application.
198-
* This build ID is generated during the `next build` process and is used
199-
* to ensure consistency across multiple instances of the application,
200-
* especially when running in containerized environments. It helps in
201-
* identifying which version of the application is being served.
202-
*
203-
* https://nextjs.org/docs/pages/building-your-application/deploying#build-cache
204-
*
205-
* @example
206-
* ```js
207-
* // cache-handler.mjs
208-
* CacheHandler.onCreation(async ({ buildId }) => {
209-
* let redisHandler;
210-
*
211-
* if (buildId) {
212-
* await client.connect();
213-
*
214-
* redisHandler = await createRedisHandler({
215-
* client,
216-
* keyPrefix: `${buildId}:`,
217-
* });
218-
* }
219-
*
220-
* const localHandler = createLruHandler();
221-
*
222-
* return {
223-
* handlers: [redisHandler, localHandler],
224-
* };
225-
* });
226-
* ```
227-
*/
228-
buildId?: string;
229-
};
230-
231-
/**
232-
* Represents a hook function that is called during the build and on start of the application.
233-
*
234-
* @param context - The {@link CacheCreationContext} object, providing contextual information about the cache creation environment,
235-
* such as server directory paths and whether the application is running in development mode.
236-
*
237-
* @returns Either a {@link CacheHandlerConfig} object or a Promise that resolves to a {@link CacheHandlerConfig},
238-
* specifying how the cache should be configured.
239-
*/
240-
export type OnCreationHook = (
241-
context: CacheCreationContext,
242-
) => Promise<CacheHandlerConfig> | CacheHandlerConfig;
243-
24427
/**
24528
* Deletes an entry from all handlers.
24629
*

packages/nextjs-cache-handler/src/handlers/cache-handler.types.ts

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type {
44
} from "next/dist/server/lib/incremental-cache";
55

66
import type FileSystemCache from "next/dist/server/lib/incremental-cache/file-system-cache";
7+
78
/**
89
* A set of time periods and timestamps for controlling cache behavior.
910
*/
@@ -49,7 +50,7 @@ export type CacheHandlerParametersGetWithTags = [
4950
* Represents an internal Next.js metadata for a `get` method.
5051
* This metadata is available in the `get` method of the cache handler.
5152
*/
52-
type HandlerGetMeta = {
53+
export type HandlerGetMeta = {
5354
/**
5455
* An array of tags that are implicitly associated with the cache entry.
5556
*/
@@ -58,7 +59,7 @@ type HandlerGetMeta = {
5859
/**
5960
* Represents a cache Handler.
6061
*/
61-
type Handler = {
62+
export type Handler = {
6263
/**
6364
* A descriptive name for the cache Handler.
6465
*/
@@ -159,7 +160,7 @@ type Handler = {
159160
/**
160161
* Represents the parameters for Time-to-Live (TTL) configuration.
161162
*/
162-
type TTLParameters = {
163+
export type TTLParameters = {
163164
/**
164165
* The time in seconds for when the cache entry becomes stale.
165166
*
@@ -182,7 +183,7 @@ type TTLParameters = {
182183
/**
183184
* Configuration options for the {@link CacheHandler}.
184185
*/
185-
type CacheHandlerConfig = {
186+
export type CacheHandlerConfig = {
186187
/**
187188
* An array of cache instances that conform to the Handler interface.
188189
* Multiple caches can be used to implement various caching strategies or layers.
@@ -196,7 +197,7 @@ type CacheHandlerConfig = {
196197
/**
197198
* Contextual information provided during cache creation, including server directory paths and environment mode.
198199
*/
199-
type CacheCreationContext = {
200+
export type CacheCreationContext = {
200201
/**
201202
* The absolute path to the Next.js server directory.
202203
*/
@@ -249,7 +250,7 @@ type CacheCreationContext = {
249250
* @returns Either a {@link CacheHandlerConfig} object or a Promise that resolves to a {@link CacheHandlerConfig},
250251
* specifying how the cache should be configured.
251252
*/
252-
type OnCreationHook = (
253+
export type OnCreationHook = (
253254
context: CacheCreationContext,
254255
) => Promise<CacheHandlerConfig> | CacheHandlerConfig;
255256
declare class CacheHandler implements NextCacheHandler {
@@ -345,12 +346,3 @@ export type CacheHandlerValue = NextCacheHandlerValue & {
345346
*/
346347
lifespan: LifespanParameters | null;
347348
};
348-
349-
export {
350-
type CacheCreationContext,
351-
CacheHandler,
352-
type CacheHandlerConfig,
353-
type Handler,
354-
type OnCreationHook,
355-
type TTLParameters,
356-
};

packages/nextjs-cache-handler/src/handlers/composite.ts

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,5 @@
1-
import { CacheHandlerValue, Handler } from "./cache-handler.types";
2-
3-
export type CreateCompositeHandlerOptions = {
4-
/**
5-
* A collection of handlers to manage the cache.
6-
*/
7-
handlers: Handler[];
8-
9-
/**
10-
* Strategy to determine which handler to use for the set operation.
11-
* Defaults to the first handler if not provided.
12-
* @param data - The data to be saved in one of the handlers. See {@link CacheHandlerValue}.
13-
* @returns The index of the handler for the set operation.
14-
*/
15-
setStrategy: (data: CacheHandlerValue) => number;
16-
};
1+
import { Handler } from "./cache-handler.types";
2+
import { CreateCompositeHandlerOptions } from "./composite.types";
173

184
/**
195
* Creates a composite Handler for managing cache operations using multiple handlers.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Handler, CacheHandlerValue } from "./cache-handler.types";
2+
3+
export type CreateCompositeHandlerOptions = {
4+
/**
5+
* A collection of handlers to manage the cache.
6+
*/
7+
handlers: Handler[];
8+
9+
/**
10+
* Strategy to determine which handler to use for the set operation.
11+
* Defaults to the first handler if not provided.
12+
* @param data - The data to be saved in one of the handlers. See {@link CacheHandlerValue}.
13+
* @returns The index of the handler for the set operation.
14+
*/
15+
setStrategy: (data: CacheHandlerValue) => number;
16+
};

packages/nextjs-cache-handler/src/handlers/local-lru.ts

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { LRUCache } from "lru-cache";
22
import { CacheHandlerValue, Handler } from "./cache-handler.types";
33
import { NEXT_CACHE_IMPLICIT_TAG_ID } from "../helpers/const";
4+
import { LruCacheOptions } from "./local-lru.types";
45

56
const MAX_ITEMS_NUMBER = 1000;
67
const MAX_ITEM_SIZE_BYTES = 100 * 1024 * 1024;
@@ -33,28 +34,6 @@ export function createConfiguredCache<CacheValueType extends object | string>(
3334
});
3435
}
3536

36-
/**
37-
* Configuration options for the LRU cache.
38-
*/
39-
export type LruCacheOptions = {
40-
/**
41-
* Optional. Maximum number of items the cache can hold.
42-
*
43-
* @default 1000
44-
*/
45-
maxItemsNumber?: number;
46-
/**
47-
* Optional. Maximum size in bytes for each item in the cache.
48-
*
49-
* @default 104857600 // 100 Mb
50-
*/
51-
maxItemSizeBytes?: number;
52-
};
53-
/**
54-
* @deprecated Use {@link LruCacheOptions} instead.
55-
*/
56-
export type LruCacheHandlerOptions = LruCacheOptions;
57-
5837
/**
5938
* Creates an LRU (Least Recently Used) cache Handler.
6039
*
@@ -77,8 +56,6 @@ export type LruCacheHandlerOptions = LruCacheOptions;
7756
*
7857
* @remarks
7958
* - Use this Handler as a fallback for any remote store Handler.
80-
*
81-
* @since 1.0.0
8259
*/
8360
export default function createHandler({
8461
...lruOptions

0 commit comments

Comments
 (0)