[READ-ONLY] a fast, modern browser for the npm registry
at main 39 lines 1.0 kB view raw
1import type { Redis } from '@upstash/redis' 2 3/** 4 * Redis cache storage with TTL handled by redis for use in production 5 */ 6export class RedisCacheAdapter implements CacheAdapter { 7 private readonly redis: Redis 8 private readonly prefix: string 9 10 formatKey(key: string): string { 11 return `${this.prefix}:${key}` 12 } 13 14 constructor(redis: Redis, prefix: string) { 15 this.redis = redis 16 this.prefix = prefix 17 } 18 19 async get<T>(key: string): Promise<T | undefined> { 20 const formattedKey = this.formatKey(key) 21 const value = await this.redis.get<T>(formattedKey) 22 if (!value) return 23 return value 24 } 25 26 async set<T>(key: string, value: T, ttl?: number): Promise<void> { 27 const formattedKey = this.formatKey(key) 28 if (ttl) { 29 await this.redis.setex(formattedKey, ttl, value) 30 } else { 31 await this.redis.set(formattedKey, value) 32 } 33 } 34 35 async delete(key: string): Promise<void> { 36 const formattedKey = this.formatKey(key) 37 await this.redis.del(formattedKey) 38 } 39}