Make dufflepud optional, fetch zappers/handles directly

This commit is contained in:
Jon Staab
2024-09-05 15:26:45 -07:00
parent ed7efac977
commit 18db1421a9
6 changed files with 130 additions and 37 deletions
+37 -14
View File
@@ -2,26 +2,44 @@ import {writable, derived} from 'svelte/store'
import {withGetter} from '@welshman/store'
import {type Zapper} from '@welshman/util'
import {type SubscribeRequest} from "@welshman/net"
import {ctx, uniq, identity, bech32ToHex, tryCatch, uniqBy, batcher, postJson} from '@welshman/lib'
import {ctx, fetchJson, uniq, bech32ToHex, hexToBech32, tryCatch, batcher, postJson} from '@welshman/lib'
import {collection} from './collection'
import {deriveProfile} from './profiles'
export const zappers = withGetter(writable<Zapper[]>([]))
export const fetchZappers = (lnurls: string[]) => {
export const fetchZappers = async (lnurls: string[]) => {
const base = ctx.app.dufflepudUrl!
const zappersByLnurl = new Map<string, Zapper>()
if (!base) {
throw new Error("ctx.app.dufflepudUrl is required to fetch zapper info")
// Attempt fetching directly first
const results = await Promise.all(
lnurls.map(async lnurl => {
const hexUrl = tryCatch(() => bech32ToHex(lnurl))
const info = hexUrl ? await fetchJson(hexUrl) : undefined
return {lnurl, hexUrl, info}
})
)
const dufflepudLnurls: string[] = []
// If we got a response, great, if not (due to CORS), proxy via dufflepud
for (const {lnurl, hexUrl, info} of results) {
if (info) {
zappersByLnurl.set(lnurl, info)
} else if (hexUrl) {
dufflepudLnurls.push(hexUrl)
}
}
const zappersByLnurl = new Map<string, Zapper>()
const res: any = postJson(`${base}/zapper/info`, {
lnurls: lnurls.map(lnurl => tryCatch(() => bech32ToHex(lnurl))).filter(identity),
})
// Fetch via dufflepud if we have an endpoint
if (base && dufflepudLnurls.length > 0) {
const res: any = await postJson(`${base}/zapper/info`, {lnurls: dufflepudLnurls})
for (const {lnurl, info} of res?.data || []) {
tryCatch(() => zappersByLnurl.set(bech32ToHex(lnurl), info))
for (const {lnurl, info} of res?.data || []) {
tryCatch(() => zappersByLnurl.set(hexToBech32("lnurl", lnurl), info))
}
}
return zappersByLnurl
@@ -39,12 +57,17 @@ export const {
const fresh = await fetchZappers(uniq(lnurls))
const stale = zappersByLnurl.get()
const items: Zapper[] = lnurls.map(lnurl => {
const zapper = fresh.get(lnurl) || stale.get(lnurl) || {}
const newZapper = fresh.get(lnurl)
const oldZapper = stale.get(lnurl)
return {...zapper, lnurl}
if (newZapper) {
stale.set(lnurl, {...newZapper, lnurl})
}
return {...oldZapper, ...newZapper, lnurl}
})
zappers.update($zappers => uniqBy($zapper => $zapper.lnurl, [...$zappers, ...items]))
zappers.set(Array.from(stale.values()))
return items
}),
@@ -60,7 +83,7 @@ export const deriveZapperForPubkey = (pubkey: string, request: Partial<Subscribe
loadZapper($profile.lnurl)
return $zappersByLnurl.get($profile?.lnurl)
return $zappersByLnurl.get($profile.lnurl)
}
)