Thread viewer for Bluesky
1/**
2 * Caches the mapping of handles to DIDs to avoid unnecessary API calls to resolveHandle or getProfile.
3 */
4
5type HandleMap = Record<string, string>;
6
7export class HandleCache {
8 cache?: HandleMap
9
10 prepareCache(): asserts this is { cache: HandleMap } {
11 if (!this.cache) {
12 let savedCache = localStorage.getItem('handleCache');
13 this.cache = (savedCache ? JSON.parse(savedCache) : {}) as HandleMap;
14 }
15 }
16
17 saveCache() {
18 localStorage.setItem('handleCache', JSON.stringify(this.cache));
19 }
20
21 getHandleDid(handle: string): string | undefined {
22 this.prepareCache();
23 return this.cache[handle];
24 }
25
26 setHandleDid(handle: string, did: string) {
27 this.prepareCache();
28 this.cache[handle] = did;
29 this.saveCache();
30 }
31
32 findHandleByDid(did: string) {
33 this.prepareCache();
34 let found = Object.entries(this.cache).find((e) => e[1] == did);
35 return found ? found[0] : undefined;
36 }
37}