about summary refs log tree commit diff
path: root/src/state/models/link-metas-view.ts
diff options
context:
space:
mode:
authorPaul Frazee <pfrazee@gmail.com>2022-11-23 17:01:00 -0600
committerPaul Frazee <pfrazee@gmail.com>2022-11-23 17:01:00 -0600
commitf5ff0fd2749b5f9ebd9c6b4129513ff8ad577c00 (patch)
treed49af79643e7173bfe126354c93a6c86522fe3d7 /src/state/models/link-metas-view.ts
parent89638dbd188023851e67d818dcd4c23204e3c70c (diff)
downloadvoidsky-f5ff0fd2749b5f9ebd9c6b4129513ff8ad577c00.tar.zst
Add link embeds to posts
Diffstat (limited to 'src/state/models/link-metas-view.ts')
-rw-r--r--src/state/models/link-metas-view.ts44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/state/models/link-metas-view.ts b/src/state/models/link-metas-view.ts
new file mode 100644
index 000000000..0187f4260
--- /dev/null
+++ b/src/state/models/link-metas-view.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'
+
+type CacheValue = Promise<LinkMeta> | LinkMeta
+export class LinkMetasViewModel {
+  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(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
+    }
+  }
+}