PinListRepositoryImpl.ts raw

   1  import { PinListRepository, PinList, Pubkey, tryToPinList } 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 PinListRepository
   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 PinListRepositoryImpl implements PinListRepository {
  14    constructor(private readonly deps: RepositoryDependencies) {}
  15  
  16    async findByOwner(pubkey: Pubkey): Promise<PinList | null> {
  17      // Try cache first
  18      const cachedEvent = await indexedDb.getReplaceableEvent(pubkey.hex, kinds.Pinlist)
  19      if (cachedEvent) {
  20        const pinList = tryToPinList(cachedEvent)
  21        if (pinList) return pinList
  22      }
  23  
  24      // Fetch from relays
  25      const event = await client.fetchPinListEvent(pubkey.hex)
  26      if (!event) return null
  27  
  28      // Update cache
  29      await indexedDb.putReplaceableEvent(event)
  30  
  31      return tryToPinList(event)
  32    }
  33  
  34    async save(pinList: PinList): Promise<void> {
  35      const draftEvent = pinList.toDraftEvent()
  36      const publishedEvent = await this.deps.publish(draftEvent)
  37  
  38      // Update cache
  39      await indexedDb.putReplaceableEvent(publishedEvent)
  40    }
  41  }
  42