about summary refs log tree commit diff
path: root/src/state/models/cache
diff options
context:
space:
mode:
Diffstat (limited to 'src/state/models/cache')
-rw-r--r--src/state/models/cache/profiles-view.ts52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/state/models/cache/profiles-view.ts b/src/state/models/cache/profiles-view.ts
new file mode 100644
index 000000000..b4bd70db5
--- /dev/null
+++ b/src/state/models/cache/profiles-view.ts
@@ -0,0 +1,52 @@
+import {makeAutoObservable} from 'mobx'
+import {LRUMap} from 'lru_map'
+import {RootStoreModel} from '../root-store'
+import {AppBskyActorGetProfile as GetProfile} from '@atproto/api'
+
+type CacheValue = Promise<GetProfile.Response> | GetProfile.Response
+export class ProfilesCache {
+  cache: LRUMap<string, CacheValue> = new LRUMap(100)
+
+  constructor(public rootStore: RootStoreModel) {
+    makeAutoObservable(
+      this,
+      {
+        rootStore: false,
+        cache: false,
+      },
+      {autoBind: true},
+    )
+  }
+
+  // public api
+  // =
+
+  async getProfile(did: string) {
+    const cached = this.cache.get(did)
+    if (cached) {
+      try {
+        return await cached
+      } catch (e) {
+        // ignore, we'll try again
+      }
+    }
+    try {
+      const promise = this.rootStore.agent.getProfile({
+        actor: did,
+      })
+      this.cache.set(did, promise)
+      const res = await promise
+      this.cache.set(did, res)
+      return res
+    } catch (e) {
+      this.cache.delete(did)
+      throw e
+    }
+  }
+
+  overwrite(did: string, res: GetProfile.Response) {
+    if (this.cache.has(did)) {
+      this.cache.set(did, res)
+    }
+  }
+}