diff options
Diffstat (limited to 'src/state/models/cache/link-metas.ts')
-rw-r--r-- | src/state/models/cache/link-metas.ts | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/state/models/cache/link-metas.ts b/src/state/models/cache/link-metas.ts new file mode 100644 index 000000000..607968c80 --- /dev/null +++ b/src/state/models/cache/link-metas.ts @@ -0,0 +1,44 @@ +import {makeAutoObservable} from 'mobx' +import {LRUMap} from 'lru_map' +import {RootStoreModel} from '../root-store' +import {LinkMeta, getLinkMeta} from 'lib/link-meta/link-meta' + +type CacheValue = Promise<LinkMeta> | LinkMeta +export class LinkMetasCache { + cache: LRUMap<string, CacheValue> = new LRUMap(100) + + constructor(public rootStore: RootStoreModel) { + makeAutoObservable( + this, + { + rootStore: false, + cache: false, + }, + {autoBind: true}, + ) + } + + // public api + // = + + async getLinkMeta(url: string) { + const cached = this.cache.get(url) + if (cached) { + try { + return await cached + } catch (e) { + // ignore, we'll try again + } + } + try { + const promise = getLinkMeta(this.rootStore, url) + this.cache.set(url, promise) + const res = await promise + this.cache.set(url, res) + return res + } catch (e) { + this.cache.delete(url) + throw e + } + } +} |