// @ts-check /// // 前回の処理時刻(storage に保存)より後に変更された予定だけを読む。取消(deleted)も数える。 // bookings.read の題名・説明には外部利用者の名前が入り得るため、ここでは件数だけを返し、ログにも storage にも書かない。 const CURSOR_KEY = "lastProcessedAt"; const DAY_MS = 24 * 60 * 60 * 1000; /** @param {Niho.Env} env */ export default async function (env) { const lookaheadDays = typeof env.config.lookaheadDays === "number" ? env.config.lookaheadDays : 30; const startedAt = new Date(); // bookings.list の期間は 93 日以内。昨日から lookaheadDays 日先まで読む。 const from = new Date(startedAt.getTime() - DAY_MS).toISOString(); const to = new Date(startedAt.getTime() + lookaheadDays * DAY_MS).toISOString(); const saved = await env.storage.get(CURSOR_KEY); const updatedSince = typeof saved === "string" ? saved : undefined; let changed = 0; let cancelled = 0; /** @type {string | undefined} */ let cursor; do { const page = await env.bookings.list({ from, to, includeDeleted: true, ...(updatedSince ? { updatedSince } : {}), ...(cursor ? { cursor } : {}), }); for (const booking of page.bookings) { if (booking.deleted) cancelled += 1; else changed += 1; } cursor = page.nextCursor ?? undefined; } while (cursor); // 次回は、今回の開始時刻より後に変更されたものだけを読む。 await env.storage.set(CURSOR_KEY, startedAt.toISOString()); return { changed, cancelled, since: updatedSince ?? null }; }