migrate to ndk

This commit is contained in:
Ren Amamiya
2023-06-08 18:09:36 +07:00
parent 75a33d205a
commit 0ba9877785
53 changed files with 2749 additions and 930 deletions

View File

@@ -1,56 +1,31 @@
import { RelayContext } from "@shared/relayProvider";
import { useActiveAccount } from "@stores/accounts";
import { READONLY_RELAYS } from "@stores/constants";
import { createNote, getNoteByID } from "@utils/storage";
import { getParentID } from "@utils/transform";
import { useContext } from "react";
import useSWR from "swr";
import useSWRSubscription from "swr/subscription";
const fetcher = ([, id]) => getNoteByID(id);
const fetcher = async ([, ndk, id]) => {
const result = await getNoteByID(id);
if (result) {
return result;
} else {
const event = await ndk.fetchEvent(id);
await createNote(
event.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
);
event["event_id"] = event.id;
return event;
}
};
export function useEvent(id: string) {
const pool: any = useContext(RelayContext);
const account = useActiveAccount((state: any) => state.account);
const ndk = useContext(RelayContext);
const { data } = useSWR(["note", ndk, id], fetcher);
const { data: cache } = useSWR(["event", id], fetcher);
const { data: newest } = useSWRSubscription(
!cache ? id : null,
(key, { next }) => {
const unsubscribe = pool.subscribe(
[
{
ids: [key],
},
],
READONLY_RELAYS,
(event: any) => {
const parentID = getParentID(event.tags, event.id);
// insert event to local database
createNote(
event.id,
account.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
);
// update state
next(null, event);
},
undefined,
undefined,
{
unsubscribeOnEose: true,
},
);
return () => {
unsubscribe();
};
},
);
return cache ? cache : newest;
return data;
}