Skip to content
← Public packages

@kentcdodds/audible

Personal Audible library app — browser re-auth, library, wishlist, NAS archive stub.

src/__tests__/nas-status-cache.test.ts

66 lines · 1.6 KB · TypeScript
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
	NAS_MAX_AGE_MS,
	NAS_SOFT_TTL_MS,
	classifyCacheAge,
	emptyNasStatusCacheStore,
	lookupNasStatusCache,
	putNasStatusCacheEntry,
	titleCacheKey,
} from '../nas-status-cache-policy.ts'

test('titleCacheKey normalizes case and trim', () => {
	assert.equal(titleCacheKey('  Hatchet '), 'hatchet')
})

test('classifyCacheAge soft TTL / stale / expired', () => {
	const now = 1_000_000_000
	assert.deepEqual(classifyCacheAge(now - 30_000, now), {
		ageMs: 30_000,
		fresh: true,
		stale: false,
		expired: false,
	})
	assert.deepEqual(classifyCacheAge(now - NAS_SOFT_TTL_MS - 1, now), {
		ageMs: NAS_SOFT_TTL_MS + 1,
		fresh: false,
		stale: true,
		expired: false,
	})
	assert.deepEqual(classifyCacheAge(now - NAS_MAX_AGE_MS - 1, now), {
		ageMs: NAS_MAX_AGE_MS + 1,
		fresh: false,
		stale: false,
		expired: true,
	})
})

test('lookup serves by title and asin until max age', () => {
	const now = Date.now()
	const store = emptyNasStatusCacheStore()
	putNasStatusCacheEntry(store, {
		title: 'Hatchet',
		asin: 'B002UZKI96',
		nasFilename: 'Hatchet.m4b',
		onNas: true,
		checkedAt: now - 5_000,
	})
	const byTitle = lookupNasStatusCache(store, { title: 'hatchet' }, now)
	assert.equal(byTitle?.fresh, true)
	assert.equal(byTitle?.entry.onNas, true)
	const byAsin = lookupNasStatusCache(
		store,
		{ asin: 'B002UZKI96', title: 'Other' },
		now,
	)
	assert.equal(byAsin?.entry.nasFilename, 'Hatchet.m4b')
	assert.equal(
		lookupNasStatusCache(
			store,
			{ title: 'Hatchet' },
			now + NAS_MAX_AGE_MS + 10,
		),
		null,
	)
})