import type { BasePayload, Where } from 'payload' const DAY_MS = 24 * 60 * 60 * 1000 /** * Retention purge for a log collection (stats visits, consent records): at * most once a day per process, and OFF the visitor's request. * * It used to be awaited inside the hit / consent request through * `payload.delete`, which loads every expired document and deletes them one by * one — the first purge after months of traffic held a visitor's request for * as long as that took. `db.deleteMany` is a single query (these collections * have no hooks to run), started and left to finish on its own; a failure is * logged and retried on the next request. */ export function createDailyPurge(collection: string) { let lastPurge = 0 return (payload: BasePayload, where: Where): void => { const now = Date.now() if (now - lastPurge < DAY_MS) {return} lastPurge = now void Promise.resolve() .then(() => payload.db.deleteMany({ collection: collection as never, where })) .catch((err: unknown) => { lastPurge = 0 payload.logger.error(`[iapl] ${collection} retention purge failed: ${err instanceof Error ? err.message : String(err)}`) }) } }