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,12 +1,11 @@
import NDK from "@nostr-dev-kit/ndk";
import { RelayContext } from "@shared/relayProvider";
import { METADATA_RELAY } from "@stores/constants";
import { createPleb, getPleb } from "@utils/storage";
import { nip19 } from "nostr-tools";
import { useContext } from "react";
import useSWR from "swr";
import useSWRSubscription from "swr/subscription";
const fetcher = async (key: string) => {
const fetcher = async ([, ndk, key]) => {
let npub: string;
if (key.substring(0, 4) === "npub") {
@@ -18,59 +17,27 @@ const fetcher = async (key: string) => {
const current = Math.floor(Date.now() / 1000);
const result = await getPleb(npub);
if (result && result.created_at + 86400 < current) {
if (result && result.created_at + 86400 > current) {
return result;
} else {
return null;
const user = ndk.getUser({ npub });
await user.fetchProfile();
await createPleb(key, user.profile);
return user.profile;
}
};
export function useProfile(key: string) {
const pool: any = useContext(RelayContext);
const {
data: cache,
error,
isLoading,
} = useSWR(key, fetcher, {
const ndk = useContext(RelayContext);
const { data, error, isLoading } = useSWR(["profile", ndk, key], fetcher, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: true,
});
const { data: newest } = useSWRSubscription(
cache ? null : key,
(_, { next }) => {
const unsubscribe = pool.subscribe(
[
{
authors: [key],
kinds: [0],
},
],
METADATA_RELAY,
(event: { content: string }) => {
const content = JSON.parse(event.content);
// update state
next(null, content);
// save to database
createPleb(key, event);
},
undefined,
undefined,
{
unsubscribeOnEose: true,
},
);
return () => {
unsubscribe();
};
},
);
return {
user: newest ? newest : cache,
user: data,
isLoading,
isError: error,
};