UNPKG

@credo-ts/core

Version:

<p align="center"> <br /> <img alt="Credo Logo" src="https://github.com/openwallet-foundation/credo-ts/blob/c7886cb8377ceb8ee4efe8d264211e561a75072d/images/credo-logo.png" height="250px" /> </p> <h1 align="center"><b>Credo - Core</b></h1

1 lines • 2.76 kB
{"version":3,"file":"InMemoryLruCache.mjs","names":[],"sources":["../../../src/modules/cache/InMemoryLruCache.ts"],"sourcesContent":["import LRUMap from 'lru_map'\nimport type { AgentContext } from '../../agent/context'\nimport type { Cache } from './Cache'\n\nexport interface InMemoryLruCacheOptions {\n /** The maximum number of entries allowed in the cache */\n limit: number\n}\n\n/**\n * In memory LRU cache.\n *\n * This cache can be used with multiple agent context instances, however all instances will share the same cache.\n * If you need the cache to be isolated per agent context instance, make sure to use a different cache implementation.\n */\nexport class InMemoryLruCache implements Cache {\n private readonly cache: LRUMap.LRUMap<string, CacheItem>\n\n public constructor({ limit }: InMemoryLruCacheOptions) {\n this.cache = new LRUMap.LRUMap<string, CacheItem>(limit)\n }\n\n public async get<CacheValue>(_agentContext: AgentContext, key: string) {\n this.removeExpiredItems()\n const item = this.cache.get(key)\n\n // Does not exist\n if (!item) return null\n\n return item.value as CacheValue\n }\n\n public async set<CacheValue>(\n _agentContext: AgentContext,\n key: string,\n value: CacheValue,\n expiresInSeconds?: number\n ): Promise<void> {\n this.removeExpiredItems()\n let expiresDate: Date | undefined\n\n if (expiresInSeconds) {\n expiresDate = new Date()\n expiresDate.setSeconds(expiresDate.getSeconds() + expiresInSeconds)\n }\n\n this.cache.set(key, {\n expiresAt: expiresDate?.getTime(),\n value,\n })\n }\n\n public clear() {\n this.cache.clear()\n }\n\n public async remove(_agentContext: AgentContext, key: string): Promise<void> {\n this.removeExpiredItems()\n this.cache.delete(key)\n }\n\n private removeExpiredItems() {\n this.cache.forEach((value, key) => {\n if (value.expiresAt && Date.now() > value.expiresAt) {\n this.cache.delete(key)\n }\n })\n }\n}\n\ninterface CacheItem {\n expiresAt?: number\n value: unknown\n}\n"],"mappings":";;;;;;;;;;;AAeA,IAAa,mBAAb,MAA+C;CAG7C,AAAO,YAAY,EAAE,SAAkC;AACrD,OAAK,QAAQ,IAAI,OAAO,OAA0B,MAAM;;CAG1D,MAAa,IAAgB,eAA6B,KAAa;AACrE,OAAK,oBAAoB;EACzB,MAAM,OAAO,KAAK,MAAM,IAAI,IAAI;AAGhC,MAAI,CAAC,KAAM,QAAO;AAElB,SAAO,KAAK;;CAGd,MAAa,IACX,eACA,KACA,OACA,kBACe;AACf,OAAK,oBAAoB;EACzB,IAAI;AAEJ,MAAI,kBAAkB;AACpB,iCAAc,IAAI,MAAM;AACxB,eAAY,WAAW,YAAY,YAAY,GAAG,iBAAiB;;AAGrE,OAAK,MAAM,IAAI,KAAK;GAClB,WAAW,aAAa,SAAS;GACjC;GACD,CAAC;;CAGJ,AAAO,QAAQ;AACb,OAAK,MAAM,OAAO;;CAGpB,MAAa,OAAO,eAA6B,KAA4B;AAC3E,OAAK,oBAAoB;AACzB,OAAK,MAAM,OAAO,IAAI;;CAGxB,AAAQ,qBAAqB;AAC3B,OAAK,MAAM,SAAS,OAAO,QAAQ;AACjC,OAAI,MAAM,aAAa,KAAK,KAAK,GAAG,MAAM,UACxC,MAAK,MAAM,OAAO,IAAI;IAExB"}