Refactor/fix error handling, add query timeouts
This commit is contained in:
28
nostr.ts
28
nostr.ts
@@ -1,4 +1,4 @@
|
||||
import { NPool, NRelay1 } from "@nostrify/nostrify";
|
||||
import { NostrEvent, NostrFilter, NPool, NRelay1 } from "@nostrify/nostrify";
|
||||
import { nip19 } from "@nostr/tools";
|
||||
import { lookupUsernameByPubkey } from "./directory.ts";
|
||||
import config from "./config.ts";
|
||||
@@ -14,47 +14,57 @@ const relayPool = new NPool({
|
||||
eventRouter: async (_event) => [],
|
||||
});
|
||||
|
||||
async function fetchWithTimeout(filters: NostrFilter[]) {
|
||||
const timeoutPromise = new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error("relay timeout")), config.query_timeout)
|
||||
);
|
||||
const eventsPromise = relayPool.query(filters);
|
||||
|
||||
const events = await Promise.race([eventsPromise, timeoutPromise]);
|
||||
return events;
|
||||
}
|
||||
|
||||
export async function fetchReplaceableEvent(
|
||||
pubkey: string,
|
||||
identifier: string,
|
||||
) {
|
||||
let events = await relayPool.query([{
|
||||
let events = await fetchWithTimeout([{
|
||||
authors: [pubkey],
|
||||
kinds: [30023],
|
||||
"#d": [identifier],
|
||||
limit: 1,
|
||||
}]);
|
||||
}]) as NostrEvent[];
|
||||
|
||||
if (events.length > 0) {
|
||||
return events[0];
|
||||
} else {
|
||||
events = await relayPool.query([{
|
||||
events = await fetchWithTimeout([{
|
||||
authors: [pubkey],
|
||||
kinds: [30024],
|
||||
"#d": [identifier],
|
||||
limit: 1,
|
||||
}]);
|
||||
}]) as NostrEvent[];
|
||||
|
||||
return events.length > 0 ? events[0] : null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchArticlesByAuthor(pubkey: string) {
|
||||
const events = await relayPool.query([{
|
||||
const events = await fetchWithTimeout([{
|
||||
authors: [pubkey],
|
||||
kinds: [30023],
|
||||
limit: 10,
|
||||
}]);
|
||||
}]) as NostrEvent[];
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
export async function fetchProfileEvent(pubkey: string) {
|
||||
const events = await relayPool.query([{
|
||||
const events = await fetchWithTimeout([{
|
||||
authors: [pubkey],
|
||||
kinds: [0],
|
||||
limit: 1,
|
||||
}]);
|
||||
}]) as NostrEvent[];
|
||||
|
||||
return events.length > 0 ? events[0] : null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user