Skip to content

Commit d7e1438

Browse files
committed
Adds handler preparation step
Ensures handlers execute preparation tasks after configuration. This step allows handlers to perform necessary setup, such as cleaning up expired entries or stale resources, before being used.
1 parent 1c2b811 commit d7e1438

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,30 @@ export class CacheHandler implements NextCacheHandler {
649649
"Successfully created CacheHandler configuration.",
650650
);
651651
}
652+
653+
const prepareResults = await Promise.allSettled(
654+
handlersList.map((handler) => handler.prepare?.()),
655+
);
656+
657+
if (CacheHandler.#debug) {
658+
prepareResults.forEach((result, index) => {
659+
if (result.status === "rejected") {
660+
console.warn(
661+
"[CacheHandler] [handler: %s] [method: %s] %s",
662+
handlersList[index]?.name ?? `unknown-${index}`,
663+
"prepare",
664+
`Error: ${result.reason}`,
665+
);
666+
} else if (result.status === "fulfilled" && result.value !== undefined) {
667+
console.info(
668+
"[CacheHandler] [handler: %s] [method: %s] %s",
669+
handlersList[index]?.name ?? `unknown-${index}`,
670+
"prepare",
671+
"Successfully completed preparation tasks.",
672+
);
673+
}
674+
});
675+
}
652676
}
653677

654678
/**

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,15 @@ export type Handler = {
173173
* @returns A Promise that resolves when the cache entry has been successfully deleted.
174174
*/
175175
delete?: (key: string) => Promise<void>;
176+
177+
/**
178+
* Prepares the handler for use, such as cleaning up expired entries or stale resources.
179+
* This method is optional and will be automatically called by the `CacheHandler` class after handlers are configured.
180+
* Handlers can use this to perform one-time setup tasks, remove stale entries, or prepare internal state.
181+
*
182+
* @returns A Promise that resolves when the preparation tasks have been completed.
183+
*/
184+
prepare?: () => Promise<void>;
176185
};
177186
/**
178187
* Represents the parameters for Time-to-Live (TTL) configuration.

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,5 +328,8 @@ export default function createHandler({
328328
.hDel(keyPrefix + sharedTagsTtlKey, key),
329329
]);
330330
},
331+
async prepare() {
332+
await revalidateSharedKeys();
333+
},
331334
};
332335
}

0 commit comments

Comments
 (0)