freshyo/apps/backend/src/jobs/cache-creator.ts
2026-03-29 12:12:51 +05:30

43 lines
1.2 KiB
TypeScript

import dayjs from 'dayjs'
import { initializeAllStores } from '@/src/stores/store-initializer'
const LAST_TRIGGER_KEY = 'lastTrigger'
const ALARM_DELAY_MINUTES = 0.5
// const ALARM_DELAY_MINUTES = 3
export class CacheCreator {
private state: any
constructor(state: any) {
this.state = state
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url)
if (request.method === 'POST' && url.pathname === '/schedule') {
const now = Date.now()
await this.state.storage.put(LAST_TRIGGER_KEY, now)
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
await this.state.storage.setAlarm(alarmAt)
return new Response('OK')
}
if (request.method === 'POST' && url.pathname === '/clear') {
await this.state.storage.deleteAll()
return new Response('OK')
}
return new Response('CacheCreator ready', { status: 200 })
}
async alarm(): Promise<void> {
const lastTrigger = await this.state.storage.get(LAST_TRIGGER_KEY)
if (!lastTrigger) {
return
}
const threshold = dayjs().subtract(ALARM_DELAY_MINUTES, 'minute')
if (dayjs(lastTrigger).isBefore(threshold)) {
await initializeAllStores()
}
}
}