at main 2.6 kB view raw
1import { logger } from './logger'; 2import { env } from '$env/dynamic/private'; 3import { GlideClient, TimeUnit } from '@valkey/valkey-glide'; 4 5export const SESSION_STORE = 'atp_sessions:'; 6export const STATE_STORE = 'atp_states:'; 7 8 9let valKeyClient: Promise<GlideClient> | null = null; 10 11 12export const getAValKeyClient = async () => { 13 if (!valKeyClient) { 14 valKeyClient = (async () => { 15 logger.info('Creating valkey client'); 16 17 const addresses = [ 18 { 19 host: env.REDIS_HOST ?? 'localhost', 20 // @ts-expect-error Going to leave it to the redis client to throw a run time error for this since 21 // it is a run time error to not be able to have redis to connect 22 port: env.REDIS_PORT as number ?? 6379 23 }, 24 ]; 25 26 return await GlideClient.createClient({ 27 addresses, 28 credentials: env.REDIS_PASSWORD ? { password: env.REDIS_PASSWORD } : undefined, 29 useTLS: env.REDIS_TLS === 'true', 30 //This may be a bit extreme, will see 31 requestTimeout: 500, // 500ms timeout 32 }); 33 })(); 34 } 35 return valKeyClient; 36}; 37 38 39export class Cache { 40 41 valKeyClient: GlideClient; 42 //Set if the cache set should have an expiration 43 expire: number | undefined; 44 cachePrefix: string; 45 46 47 constructor(glideClient: GlideClient, cachePrefix: string, expire: number | undefined = undefined) { 48 this.valKeyClient = glideClient; 49 this.expire = expire; 50 this.cachePrefix = cachePrefix; 51 } 52 53 $key(key: string) { 54 return `${this.cachePrefix}${key}`; 55 } 56 57 async get(key: string) { 58 const result = await this.valKeyClient.get(this.$key(key)); 59 if(result){ 60 return result.toString(); 61 } 62 return undefined; 63 } 64 65 async set(key: string, value: string, customExpire?: number) { 66 const expireSeconds = customExpire ?? this.expire; 67 const expiryOptions = expireSeconds ? 68 { 69 expiry: { 70 type: TimeUnit.Seconds, 71 count: expireSeconds 72 } 73 } : undefined; 74 return await this.valKeyClient.set(this.$key(key), value, expiryOptions); 75 } 76 77 async delete(key: string) { 78 await this.valKeyClient.del([this.$key(key)]); 79 } 80 81 async refreshExpiry(key: string, seconds: number) { 82 await this.valKeyClient.expire(this.$key(key), seconds); 83 } 84 85}