feat: group metadata query
This commit is contained in:
@@ -1,43 +1,54 @@
|
||||
import { commands } from "@/commands.gen";
|
||||
import type { Metadata } from "@/types";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import { useMemo } from "react";
|
||||
|
||||
export function useProfile(pubkey: string, embed?: string) {
|
||||
const {
|
||||
isLoading,
|
||||
isError,
|
||||
data: profile,
|
||||
} = useQuery({
|
||||
queryKey: ["metadata", "profile", pubkey],
|
||||
export function useProfile(pubkey: string, data?: string) {
|
||||
const hex = useMemo(() => {
|
||||
try {
|
||||
const normalized = pubkey.replace("nostr:", "").replace(/[^\w\s]/gi, "");
|
||||
const decoded = nip19.decode(normalized);
|
||||
|
||||
switch (decoded.type) {
|
||||
case "npub":
|
||||
return decoded.data;
|
||||
case "nprofile":
|
||||
return decoded.data.pubkey;
|
||||
case "naddr":
|
||||
return decoded.data.pubkey;
|
||||
default:
|
||||
return pubkey;
|
||||
}
|
||||
} catch {
|
||||
return pubkey;
|
||||
}
|
||||
}, [pubkey]);
|
||||
|
||||
const { isLoading, data: profile } = useQuery({
|
||||
queryKey: ["profile", hex],
|
||||
queryFn: async () => {
|
||||
if (embed) {
|
||||
const metadata: Metadata = JSON.parse(embed);
|
||||
if (data) {
|
||||
const metadata: Metadata = JSON.parse(data);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
let normalizedId = pubkey.replace("nostr:", "").replace(/[^\w\s]/gi, "");
|
||||
|
||||
if (normalizedId.startsWith("nprofile")) {
|
||||
const decoded = nip19.decode(normalizedId);
|
||||
|
||||
if (decoded.type === "nprofile") {
|
||||
normalizedId = decoded.data.pubkey;
|
||||
}
|
||||
}
|
||||
|
||||
const query = await commands.getProfile(normalizedId, false);
|
||||
const query = await commands.getProfile(hex);
|
||||
|
||||
if (query.status === "ok") {
|
||||
return JSON.parse(query.data) as Metadata;
|
||||
const metadata: Metadata = JSON.parse(query.data);
|
||||
return metadata;
|
||||
} else {
|
||||
throw new Error(query.error);
|
||||
await getCurrentWindow().emit("request_metadata", { id: hex });
|
||||
return {};
|
||||
}
|
||||
},
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
enabled: !!hex,
|
||||
});
|
||||
|
||||
return { isLoading, isError, profile };
|
||||
return { isLoading, profile };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user