Caching
With the new weakref's, it feels stupid to keep a reference to an cached object, because this way, it will never be
deleted in the memory. Working with TTL's and such feel like a hack and not that practical.
Lets (ab)use the garbage collector for caching. What would be best for caching, is a WeakMap with primitive types. With
the modern stuff of WeakRef's, that's possible.
Abstract example
import {WeakCache} from 'weak-cache';
type DBModel<T> = { findOne(filter: { _id: string }): Promise<T> };
abstract class Repository<T> {
private cache = new WeakCache<string, T>;
constructor(private dbModel: DBModel) {
}
async fetch(id: string) {
const cached = this.cache.get(id);
if (cached) return cached;
const fresh = await this.dbModel.findOne({_id: id});
if (fresh) this.cache.set(id, fresh);
return fresh;
}
async getAllModelsInMemory() {
return Array.from(this.cache.values());
}
}