Break down relay utils, replace removeNil with removeUndefined

This commit is contained in:
Jon Staab
2025-11-11 14:05:30 -08:00
parent 4c1c138329
commit e582d46afd
8 changed files with 81 additions and 42 deletions
+52 -24
View File
@@ -1,6 +1,15 @@
import {writable, derived} from "svelte/store"
import {
uniq,
removeUndefined,
prop,
indexBy,
batcher,
fetchJson,
postJson,
Maybe,
} from "@welshman/lib"
import {withGetter} from "@welshman/store"
import {uniq, batcher, postJson} from "@welshman/lib"
import {RelayProfile} from "@welshman/util"
import {normalizeRelayUrl, displayRelayUrl, displayRelayProfile, isRelayUrl} from "@welshman/util"
import {collection} from "@welshman/store"
@@ -8,36 +17,55 @@ import {appContext} from "./context.js"
export const relays = withGetter(writable<RelayProfile[]>([]))
export const fetchRelayProfiles = async (urls: string[]) => {
export const fetchRelayProfileDirectly = async (url: string): Promise<Maybe<RelayProfile>> => {
try {
return fetchJson(url.replace(/^ws/, "http"), {
headers: {
Accept: "application/nostr+json",
},
})
} catch (e) {
// pass
}
}
export const fetchRelayProfilesDirectly = async (
urls: string[],
): Promise<Map<string, RelayProfile>> =>
indexBy(
prop("url"),
removeUndefined(
await Promise.all(
urls.map(async url => {
const profile = await fetchRelayProfileDirectly(url)
if (profile) {
return {...profile, url}
}
}),
),
),
)
export const fetchRelayProfilesUsingProxy = async (
proxy: string,
urls: string[],
): Promise<Map<string, RelayProfile>> => {
const profilesByUrl = new Map<string, RelayProfile>()
const res: any = await postJson(`${proxy}/relay/info`, {urls})
if (appContext.dufflepudUrl) {
const res: any = await postJson(`${appContext.dufflepudUrl}/relay/info`, {urls})
for (const {url, info} of res?.data || []) {
profilesByUrl.set(url, info)
}
} else {
await Promise.all(
urls.map(async url => {
try {
const res = await fetch(url.replace(/^ws/, "http"), {
headers: {
Accept: "application/nostr+json",
},
})
profilesByUrl.set(url, await res.json())
} catch (e) {
// pass
}
}),
)
for (const {url, info} of res?.data || []) {
profilesByUrl.set(url, info)
}
return profilesByUrl
}
export const fetchRelayProfiles = (urls: string[]) =>
appContext.dufflepudUrl
? fetchRelayProfilesUsingProxy(appContext.dufflepudUrl, urls)
: fetchRelayProfilesDirectly(urls)
export const {
indexStore: relaysByUrl,
deriveItem: deriveRelay,