BookmarkListRepositoryImpl.ts raw
1 import { BookmarkListRepository, BookmarkList, Pubkey, tryToBookmarkList } from '@/domain'
2 import client from '@/services/client.service'
3 import indexedDb from '@/services/indexed-db.service'
4 import { kinds } from 'nostr-tools'
5 import { RepositoryDependencies } from './types'
6
7 /**
8 * IndexedDB + Relay implementation of BookmarkListRepository
9 *
10 * Uses IndexedDB for local caching and the client service for relay fetching.
11 * Save operations publish to relays and update the local cache.
12 */
13 export class BookmarkListRepositoryImpl implements BookmarkListRepository {
14 constructor(private readonly deps: RepositoryDependencies) {}
15
16 async findByOwner(pubkey: Pubkey): Promise<BookmarkList | null> {
17 // Try cache first
18 const cachedEvent = await indexedDb.getReplaceableEvent(pubkey.hex, kinds.BookmarkList)
19 if (cachedEvent) {
20 const bookmarkList = tryToBookmarkList(cachedEvent)
21 if (bookmarkList) return bookmarkList
22 }
23
24 // Fetch from relays
25 const event = await client.fetchBookmarkListEvent(pubkey.hex)
26 if (!event) return null
27
28 // Update cache
29 await indexedDb.putReplaceableEvent(event)
30
31 return tryToBookmarkList(event)
32 }
33
34 async save(bookmarkList: BookmarkList): Promise<void> {
35 const draftEvent = bookmarkList.toDraftEvent()
36 const publishedEvent = await this.deps.publish(draftEvent)
37
38 // Update cache
39 await indexedDb.putReplaceableEvent(publishedEvent)
40 }
41 }
42