Refactor/fix error handling, add query timeouts

This commit is contained in:
2024-10-25 14:25:41 +02:00
parent ec7c775e25
commit 5f5f024ae7
12 changed files with 168 additions and 113 deletions

View File

@@ -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;
}