Created
April 2, 2024 08:53
-
-
Save flxxyz/33f0e81295fe0a2d883284f72db326d7 to your computer and use it in GitHub Desktop.
javascript cache adaptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Cache { | |
addValue(key: any, value: any, ttl?: number): void | Promise<void>; | |
getValue(key: any): Promise<T>; | |
hasExpired(key: string): boolean | Promise<boolean>; | |
deleteValue(key: string): T | Promise<T>; | |
} | |
export class MemoryCache extends Map implements Cache { | |
addValue(key: any, value: any, ttl?: number) { | |
if (typeof ttl !== 'number') { | |
ttl = 60; | |
} | |
this.set(key, { | |
value, | |
createdAt: Date.now(), | |
expired: ttl * 1000, | |
}); | |
} | |
getValue(key: string) { | |
const value = this.get(key); | |
if (value?.expired && this.hasExpired(key)) { | |
this.delete(key); | |
return undefined; | |
} | |
return value?.value; | |
} | |
hasExpired(key: string) { | |
if (this.has(key)) { | |
const value = this.get(key); | |
if (value.createdAt + value.expired > Date.now()) { | |
return false; | |
} | |
} | |
return true; | |
} | |
deleteValue(key: string) { | |
return this.delete(key); | |
} | |
} | |
export const memoryCache = new MemoryCache(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RedisClientType } from 'redis'; | |
let redisClient: RedisClientType; | |
export interface Cache { | |
addValue(key: any, value: any, ttl?: number): void | Promise<void>; | |
getValue(key: any): Promise<T>; | |
hasExpired(key: string): boolean | Promise<boolean>; | |
deleteValue(key: string): T | Promise<T>; | |
} | |
export class RedisCache implements Cache { | |
async addValue(key: any, value: any, ttl?: number) { | |
if (typeof ttl !== 'number') { | |
ttl = 60; | |
} | |
await redisClient.set(key, value, { EX: ttl }); | |
} | |
async getValue(key: string) { | |
const value = await redisClient.get(key); | |
if (value === null) { | |
return undefined; | |
} | |
return value; | |
} | |
async hasExpired(key: string) { | |
if (await redisClient.exists(key)) { | |
if ((await redisClient.ttl(key)) <= 0) { | |
return true; | |
} | |
} | |
return false; | |
} | |
async deleteValue(key: string) { | |
await redisClient.del(key); | |
} | |
} | |
export const redisCache = new RedisCache(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment