|
| 1 | +import { cacheDatabaseWrapper, getCacheDatabase } from '@/libs/keyv'; |
| 2 | +import logger from '@/libs/winston'; |
| 3 | +import { CACHE_KEYS_DATABASE } from '@/constants/cache'; |
| 4 | +import { getAllMonths } from './month'; |
| 5 | + |
| 6 | +import { DbMonth } from '@/types/database'; |
| 7 | + |
| 8 | +const { getUpdatedAtCacheKey } = CACHE_KEYS_DATABASE; |
| 9 | + |
| 10 | +export const getUpdatedAt = (): string[] => getAllMonths().map((month) => month.updatedAt); |
| 11 | + |
| 12 | +export const getUpdatedAtCached = () => cacheDatabaseWrapper(getUpdatedAtCacheKey, getUpdatedAt); |
| 13 | + |
| 14 | +export const findUpdatedMonth = ( |
| 15 | + allMonths: DbMonth[], |
| 16 | + updatedAtArray: string[] |
| 17 | +): DbMonth | undefined => { |
| 18 | + const updatedAtSet = new Set(updatedAtArray); |
| 19 | + |
| 20 | + const dbMonth = allMonths.find((month) => !updatedAtSet.has(month.updatedAt)); |
| 21 | + if (dbMonth) return dbMonth; |
| 22 | + |
| 23 | + const allMonthsUpdatedAtSet = new Set(allMonths.map((month) => month.updatedAt)); |
| 24 | + const missingUpdatedAt = updatedAtArray.find( |
| 25 | + (updatedAt) => !allMonthsUpdatedAtSet.has(updatedAt) |
| 26 | + ); |
| 27 | + if (missingUpdatedAt) { |
| 28 | + return { |
| 29 | + name: 'missing-in-db', |
| 30 | + threadId: 'missing-in-db', |
| 31 | + createdAtOriginal: new Date().toISOString(), |
| 32 | + createdAt: new Date().toISOString(), |
| 33 | + updatedAt: new Date(missingUpdatedAt).toISOString(), |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + return undefined; |
| 38 | +}; |
| 39 | + |
| 40 | +export const getUpdatedMonth = async (): Promise<DbMonth | undefined> => { |
| 41 | + const allMonths = getAllMonths(); |
| 42 | + const updatedAtArrayCached = await getUpdatedAtCached(); |
| 43 | + |
| 44 | + const updatedMonth = findUpdatedMonth(allMonths, updatedAtArrayCached); |
| 45 | + |
| 46 | + return updatedMonth; |
| 47 | +}; |
| 48 | + |
| 49 | +/** This must run on every request, to detect change. */ |
| 50 | + |
| 51 | +export const clearCacheIfDatabaseUpdated = async (): Promise<DbMonth | undefined> => { |
| 52 | + const updatedMonth = await getUpdatedMonth(); |
| 53 | + |
| 54 | + if (updatedMonth) { |
| 55 | + logger.info('Database changed, clearing cache, updatedMonth:', updatedMonth); |
| 56 | + await getCacheDatabase().clear(); |
| 57 | + |
| 58 | + // populate cache again |
| 59 | + await getUpdatedAtCached(); |
| 60 | + } |
| 61 | + |
| 62 | + return updatedMonth; |
| 63 | +}; |
0 commit comments