dh_demo

DreamHanks demo project
git clone git://git.lair.cx/dh_demo
Log | Files | Refs | README

pagecache.ts (1213B)


      1 import { Token } from '@/lib/markup'
      2 import { getRedis } from '@/lib/redis'
      3 import { parseIntOrDefault } from './utils/number'
      4 
      5 const DEFAULT_CACHE_TTL = 60 * 60 // 1 hour
      6 
      7 export function pageCacheKey (textId: number) {
      8   return `pagecache:text/${textId}`
      9 }
     10 
     11 export async function hasPageCache (textId: number) {
     12   const redis = await getRedis()
     13   return (await redis.exists(pageCacheKey(textId))) === 1
     14 }
     15 
     16 export async function getPageCache (textId: number) {
     17   const redis = await getRedis()
     18   const data = await redis.get(pageCacheKey(textId))
     19   if (data === null) {
     20     return null
     21   }
     22   return JSON.parse(data) as Token[]
     23 }
     24 
     25 export async function putPageCache (textId: number, tokens: Token[]) {
     26   const redis = await getRedis()
     27   const key = pageCacheKey(textId)
     28   const data = JSON.stringify(tokens)
     29   await redis.set(key, data)
     30   await refreshCacheImpl(redis, key)
     31 }
     32 
     33 export async function refreshPageCache (textId: number) {
     34   const redis = await getRedis()
     35   await refreshCacheImpl(redis, pageCacheKey(textId))
     36 }
     37 
     38 function refreshCacheImpl (redis: Awaited<ReturnType<typeof getRedis>>, key: string) {
     39   return redis.expire(key, parseIntOrDefault(process.env.WIKI_PAGE_CACHE_TTL, DEFAULT_CACHE_TTL))
     40 }
     41