| 11 | * environments. |
| 12 | */ |
| 13 | export class MemoryCache<T> implements ProtonDriveCache<T> { |
| 14 | private entities: KeyValueCache<T> = {}; |
| 15 | private entitiesByTag: TagsCache = {}; |
| 16 | |
| 17 | async clear() { |
| 18 | this.entities = {}; |
| 19 | } |
| 20 | |
| 21 | async setEntity(key: string, value: T, tags?: string[]) { |
| 22 | this.entities[key] = value; |
| 23 | |
| 24 | for (const tag of Object.keys(this.entitiesByTag)) { |
| 25 | const index = this.entitiesByTag[tag].indexOf(key); |
| 26 | if (index !== -1) { |
| 27 | this.entitiesByTag[tag].splice(index, 1); |
| 28 | if (this.entitiesByTag[tag].length === 0) { |
| 29 | delete this.entitiesByTag[tag]; |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | if (tags) { |
| 35 | for (const tag of tags) { |
| 36 | if (!this.entitiesByTag[tag]) { |
| 37 | this.entitiesByTag[tag] = []; |
| 38 | } |
| 39 | this.entitiesByTag[tag].push(key); |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | async getEntity(key: string): Promise<T> { |
| 45 | const value = this.entities[key]; |
| 46 | if (!value) { |
| 47 | throw Error('Entity not found'); |
| 48 | } |
| 49 | return value; |
| 50 | } |
| 51 | |
| 52 | async *iterateEntities(keys: string[]): AsyncGenerator<EntityResult<T>> { |
| 53 | for (const key of keys) { |
| 54 | try { |
| 55 | const value = await this.getEntity(key); |
| 56 | yield { key, ok: true, value }; |
| 57 | } catch (error) { |
| 58 | yield { key, ok: false, error: `${error}` }; |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | async *iterateEntitiesByTag(tag: string): AsyncGenerator<EntityResult<T>> { |
| 64 | const keys = this.entitiesByTag[tag]; |
| 65 | if (!keys) { |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | // Pass copy of keys so concurrent changes to the cache do not affect |
| 70 | // results from iterating entities. |
nothing calls this directly
no outgoing calls
no test coverage detected