| 6 | } |
| 7 | |
| 8 | export class InMemoryCache implements ICache { |
| 9 | private inMemoryDb: Map<string, ICacheEntry>; |
| 10 | private static instance: InMemoryCache; |
| 11 | |
| 12 | private constructor() { |
| 13 | this.inMemoryDb = new Map<string, ICacheEntry>(); |
| 14 | } |
| 15 | |
| 16 | static getInstance() { |
| 17 | if (!this.instance) { |
| 18 | this.instance = new InMemoryCache(); |
| 19 | } |
| 20 | return this.instance; |
| 21 | } |
| 22 | |
| 23 | async set( |
| 24 | type: string, |
| 25 | args: string[], |
| 26 | value: any, |
| 27 | expirySeconds: number = parseInt(process.env.CACHE_EXPIRE_S || '100', 10), |
| 28 | ): Promise<void> { |
| 29 | const key = this.generateKey(type, args); |
| 30 | this.inMemoryDb.set(key, { |
| 31 | value, |
| 32 | expiry: new Date().getTime() + expirySeconds * 1000, |
| 33 | }); |
| 34 | } |
| 35 | |
| 36 | async get(type: string, args: string[]): Promise<any> { |
| 37 | const key = this.generateKey(type, args); |
| 38 | const entry = this.inMemoryDb.get(key); |
| 39 | if (!entry) { |
| 40 | return null; |
| 41 | } |
| 42 | if (new Date().getTime() > entry.expiry) { |
| 43 | this.inMemoryDb.delete(key); |
| 44 | return null; |
| 45 | } |
| 46 | return entry.value; |
| 47 | } |
| 48 | |
| 49 | async evict(type: string, args: string[]): Promise<null> { |
| 50 | const key = this.generateKey(type, args); |
| 51 | this.inMemoryDb.delete(key); |
| 52 | return null; |
| 53 | } |
| 54 | |
| 55 | private generateKey(type: string, args: string[]): string { |
| 56 | return `${type}:${JSON.stringify(args)}`; |
| 57 | } |
| 58 | } |
nothing calls this directly
no outgoing calls
no test coverage detected