File size: 1,708 Bytes
67edfce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import IORedis, { Redis as IOredis } from 'ioredis'
export class Redis {
private static client: Redis
private redis: IOredis
private constructor() {
this.redis = process.env.REDIS_URI ? new IORedis(process.env.REDIS_URI) : null
}
public static connect(): Redis {
if (!this.client) {
this.client = new Redis()
}
this.client.redis?.on('connect', () => console.log('redis: connected'))
this.client.redis?.on('ready', () => console.log('redis: ready'))
this.client.redis?.on('error', console.error)
return this.client
}
public async get(key: string): Promise<any> {
const result = await this.redis?.get(key)
if (!result) return null
try {
return JSON.parse(result)
} catch (error) {
return result
}
}
public async set(key: string, data: unknown, ex?: number): Promise<boolean> {
try {
if (ex) {
return await this.redis?.set(key, JSON.stringify(data), 'EX', ex) === 'OK'
} else {
return await this.redis?.set(key, JSON.stringify(data)) === 'OK'
}
} catch (error) {
if (ex) {
return await this.redis?.set(key, data as any, 'EX', ex) === 'OK'
} else {
return await this.redis?.set(key, data as any) === 'OK'
}
}
}
public async del(key: string): Promise<boolean> {
return await this.redis?.del(key) === 1
}
public async getFromCacheFirst<T>(key: string, fn: () => T | Promise<T>, ex?: number): Promise<T> {
try {
const result = await this.get(key)
if (result) return result
const data = await fn()
await this.set(key, data, ex)
return data
} catch (error) {
return await fn()
}
}
}
|