freshyo/apps/backend/tests/api/cache-products.test.ts
2026-09-26 17:50:33 +05:30

88 lines
2.7 KiB
TypeScript

/**
* products.json + stores/<id>.json — EVENTUAL cache.
*
* Product/store/banner changes go through the CACHE_CREATOR Durable Object,
* whose alarm fires ~30s later and then rebuilds the cache fire-and-forget.
* So these tests poll for the cacheVersion to advance before reading.
*/
import {
essentialConsts,
fetchCacheJson,
pollUntil,
productsCacheUrl,
storeDetailCacheUrl,
type EssentialConsts,
} from '../helpers/cache'
import { createStoreWithSku, type StoreWithSku } from '../helpers/fixtures'
interface ProductsCache {
products: { id: number; skus?: { id: number }[] }[]
count: number
}
interface StoreDetailCache {
store: { id: number }
products: unknown[]
}
describe('products.json + stores/<id>.json cache (eventual)', () => {
let store: StoreWithSku
let consts: EssentialConsts
beforeAll(async () => {
const before = await essentialConsts()
store = await createStoreWithSku()
consts = await pollUntil<EssentialConsts>(
`cacheVersion to advance past ${before.cacheVersion} after creating a product`,
async () => {
const now = await essentialConsts()
return now.cacheVersion > before.cacheVersion ? now : null
},
{ timeoutMs: 180_000, intervalMs: 5_000 }
)
}, 200_000)
it('lists the new product in products.json', async () => {
// The rebuild PUTs the files in parallel, so poll for this one to land.
const cache = await pollUntil<ProductsCache>(
`products.json at v-${consts.cacheVersion} to include product ${store.productId}`,
async () => {
try {
const body = await fetchCacheJson<ProductsCache>(
productsCacheUrl(consts, consts.cacheVersion)
)
return body.products.some((p) => p.id === store.productId) ? body : null
} catch {
return null
}
},
{ timeoutMs: 60_000, intervalMs: 3_000 }
)
expect(cache.products.some((p) => p.id === store.productId)).toBe(true)
})
it('writes stores/<id>.json for the new store', async () => {
// The version keeps advancing with every admin write, and the parallel rebuild
// may land the per-store file in a *later* version than the one captured in
// beforeAll — so resolve the current version on each attempt instead of pinning it.
const cache = await pollUntil<StoreDetailCache>(
`stores/${store.storeId}.json to appear`,
async () => {
try {
const now = await essentialConsts()
return await fetchCacheJson<StoreDetailCache>(
storeDetailCacheUrl(now, now.cacheVersion, store.storeId)
)
} catch {
return null
}
},
{ timeoutMs: 120_000, intervalMs: 5_000 }
)
expect(cache.store?.id).toBe(store.storeId)
})
})