dvm/src/job-types/relay-info.ts
2024-05-23 12:13:20 +03:00

50 lines
1.3 KiB
TypeScript

import { NDKEvent } from '@nostr-dev-kit/ndk'
import { log } from '../main.js'
import axios from 'axios'
import { RelayInfo } from '../types/index.js'
export const relayInfoJob = async (event: NDKEvent): Promise<string> => {
log('New relay-info job', event.rawEvent())
const input: string = event.tagValue('i')
let relays: string[] = []
try {
const relaysArr = JSON.parse(input)
// input is a string containing an array of strings representing multiple relay URIs
relays = relaysArr
} catch (err) {
// input is a string containing a string representing single relay URI
relays.push(input)
}
const wssPrefix = 'wss://'
const headers = {
headers: { Accept: 'application/nostr+json' }
}
const requests = relays.map((relay) => {
if (relay.startsWith(wssPrefix)) {
relay = relay.replace(wssPrefix, '')
}
return axios
.get<RelayInfo>((relay = `https://${relay}`), headers)
.catch(() => {
return axios
.get<RelayInfo>(`http://${relay}`, headers)
.catch(() => undefined)
})
})
let responses = await Promise.all(requests)
responses = responses.filter((response) => response !== undefined)
const data = responses.map((response) => response.data)
return Promise.resolve(JSON.stringify(data))
}