tiny lib to store weak referenced units
npm install weak-cache-maptypescript
import {WeakCache} from 'weak-cache';
// Just so we have some proper typing, e.g. mongoose has this implementation
type DBModel = { findOne(filter: { _id: string }): Promise };
// Imagen some abstract super class that represents a repository for a model
abstract class Repository {
private cache = new WeakCache;
constructor(private dbModel: DBModel) {
}
async fetch(id: string) {
// See if the id's model is still in memory, ifso return it
const cached = this.cache.get(id);
if (cached) return cached;
// get a fresh copy of the database model, and put it in the cache
const fresh = await this.dbModel.findOne({_id: id});
if (fresh) this.cache.set(id, fresh);
return fresh;
}
// Silly example it can loop over all weak references
async getAllModelsInMemory() {
return Array.from(this.cache.values());
}
}
``