diff --git a/lib/api/ecency-api/add-channel-to-ecency.ts b/lib/api/ecency-api/add-channel-to-ecency.ts index e141dd2..fe4939e 100644 --- a/lib/api/ecency-api/add-channel-to-ecency.ts +++ b/lib/api/ecency-api/add-channel-to-ecency.ts @@ -8,24 +8,26 @@ export function useAddChannelToEcency() { const { privateApiHost, ecencyAccessToken } = useContext(ChatContext); const queryClient = useQueryClient(); - return useMutation( - ["private-api", "add-community-channel"], - async (data: { username: string; channel_id: string; meta: any }) => { + return useMutation({ + mutationKey: ["private-api", "add-community-channel"], + mutationFn: async (data: { + username: string; + channel_id: string; + meta: any; + }) => { await axios.post(`${privateApiHost}/private-api/channel-add`, { ...data, code: ecencyAccessToken, }); return data; }, - { - onSuccess: (data) => { - queryClient.invalidateQueries({ - queryKey: ["private-api", "get-community-channel", data.username], - }); - queryClient.invalidateQueries({ - queryKey: [ChatQueries.COMMUNITY_CHANNEL, data.username], - }); - }, + onSuccess: (data) => { + queryClient.invalidateQueries({ + queryKey: ["private-api", "get-community-channel", data.username], + }); + queryClient.invalidateQueries({ + queryKey: [ChatQueries.COMMUNITY_CHANNEL, data.username], + }); }, - ); + }); } diff --git a/lib/api/ecency-api/get-community-channel-query.ts b/lib/api/ecency-api/get-community-channel-query.ts index 3508093..11f8913 100644 --- a/lib/api/ecency-api/get-community-channel-query.ts +++ b/lib/api/ecency-api/get-community-channel-query.ts @@ -6,9 +6,9 @@ import axios from "axios"; export function useGetCommunityChannelQuery(communityName?: string) { const { privateApiHost } = useContext(ChatContext); - return useQuery( - ["private-api", "get-community-channel", communityName], - () => + return useQuery({ + queryKey: ["private-api", "get-community-channel", communityName], + queryFn: () => axios .get<{ channel_id: string; @@ -17,9 +17,7 @@ export function useGetCommunityChannelQuery(communityName?: string) { meta: any; }>(`${privateApiHost}/private-api/channel/${communityName}`) .then((resp) => resp.data), - { - enabled: !!communityName, - refetchOnMount: false, - }, - ); + enabled: !!communityName, + refetchOnMount: false, + }); } diff --git a/lib/api/ecency-api/get-keys-query.ts b/lib/api/ecency-api/get-keys-query.ts index 820e191..6e9a3db 100644 --- a/lib/api/ecency-api/get-keys-query.ts +++ b/lib/api/ecency-api/get-keys-query.ts @@ -7,9 +7,9 @@ export function useGetKeysQuery() { const { privateApiHost, activeUsername, ecencyAccessToken } = useContext(ChatContext); - return useQuery( - ["private-api", "get-keys", activeUsername], - () => + return useQuery({ + queryKey: ["private-api", "get-keys", activeUsername], + queryFn: () => axios .post<{ key: string; pubkey: string; iv: string }[]>( `${privateApiHost}/private-api/chats`, @@ -18,9 +18,7 @@ export function useGetKeysQuery() { }, ) .then((resp) => resp.data[0]), - { - enabled: !!activeUsername, - refetchOnMount: false, - }, - ); + enabled: !!activeUsername, + refetchOnMount: false, + }); } diff --git a/lib/api/ecency-api/get-public-keys-query.ts b/lib/api/ecency-api/get-public-keys-query.ts index 5d724a4..c88c837 100644 --- a/lib/api/ecency-api/get-public-keys-query.ts +++ b/lib/api/ecency-api/get-public-keys-query.ts @@ -1,32 +1,30 @@ -import { useQuery } from "@tanstack/react-query"; +import {useQuery} from "@tanstack/react-query"; import axios from "axios"; -import { useContext } from "react"; -import { ChatContext } from "../../chat-context-provider"; +import {useContext} from "react"; +import {ChatContext} from "../../chat-context-provider"; export function useGetPublicKeysQuery(username?: string) { const { privateApiHost } = useContext(ChatContext); - return useQuery( - ["private-api", "get-pub-keys", username], - () => + return useQuery({ + queryKey: ["private-api", "get-pub-keys", username], + queryFn: () => axios - .get<{ pubkey: string }>( - `${privateApiHost}/private-api/chats-pub/${username}`, - ) + .get<{ + pubkey: string; + }>(`${privateApiHost}/private-api/chats-pub/${username}`) .then((resp) => resp.data), - { - enabled: !!username, - refetchOnMount: false, - }, - ); + enabled: !!username, + refetchOnMount: false, + }); } export function useGetSetOfPublicKeysQuery(usernames: string[] = []) { const { privateApiHost } = useContext(ChatContext); - return useQuery( - ["private-api", "get-pub-keys", usernames], - async () => { + return useQuery({ + queryKey: ["private-api", "get-pub-keys", usernames], + queryFn: async () => { const response = await axios.post<{ pubkey: string; username: string }[]>( `${privateApiHost}/private-api/chats-get`, { @@ -35,10 +33,8 @@ export function useGetSetOfPublicKeysQuery(usernames: string[] = []) { ); return response.data; }, - { - enabled: usernames.length > 0, - refetchOnMount: false, - initialData: [], - }, - ); + enabled: usernames.length > 0, + refetchOnMount: false, + initialData: [], + }); } diff --git a/lib/api/ecency-api/save-keys.ts b/lib/api/ecency-api/save-keys.ts index 0bf6514..f6763e4 100644 --- a/lib/api/ecency-api/save-keys.ts +++ b/lib/api/ecency-api/save-keys.ts @@ -7,9 +7,14 @@ export function useSaveKeys() { const { privateApiHost, activeUsername, ecencyAccessToken } = useContext(ChatContext); - return useMutation( - ["private-api", "save-keys"], - async (data: { key: string; pubkey: string; iv: string; meta: any }) => + return useMutation({ + mutationKey: ["private-api", "save-keys"], + mutationFn: async (data: { + key: string; + pubkey: string; + iv: string; + meta: any; + }) => axios .post<{ chat_keys: { key: string; pubkey: string; iv: string }[] }>( `${privateApiHost}/private-api/chats-add`, @@ -19,5 +24,5 @@ export function useSaveKeys() { }, ) .then((resp) => resp.data.chat_keys), - ); + }); } diff --git a/lib/live-listeners/use-live-direct-messages-listener.ts b/lib/live-listeners/use-live-direct-messages-listener.ts index 039336f..a037737 100644 --- a/lib/live-listeners/use-live-direct-messages-listener.ts +++ b/lib/live-listeners/use-live-direct-messages-listener.ts @@ -90,11 +90,11 @@ export function useLiveDirectMessagesListener() { ), ), ); - await queryClient.invalidateQueries([ + await queryClient.invalidateQueries({queryKey: [ NostrQueries.DIRECT_MESSAGES, activeUsername, contact.pubkey, - ]); + ]}); }, { enabled: !!publicKey && !!privateKey }, ); diff --git a/lib/live-listeners/use-live-public-messages-listener.ts b/lib/live-listeners/use-live-public-messages-listener.ts index e9cb801..a025d48 100644 --- a/lib/live-listeners/use-live-public-messages-listener.ts +++ b/lib/live-listeners/use-live-public-messages-listener.ts @@ -52,11 +52,11 @@ export function useLivePublicMessagesListener() { ), ), ); - await queryClient.invalidateQueries([ + await queryClient.invalidateQueries({queryKey: [ NostrQueries.PUBLIC_MESSAGES, activeUsername, channel.id, - ]); + ]}); }, { enabled: !!publicKey && !!privateKey }, ); diff --git a/lib/mutations/add-community-channel.ts b/lib/mutations/add-community-channel.ts index 037d3dd..c6193e4 100644 --- a/lib/mutations/add-community-channel.ts +++ b/lib/mutations/add-community-channel.ts @@ -24,59 +24,65 @@ export function useAddCommunityChannel(channel?: Channel) { () => {}, ); - return useMutation(["chats/add-community-channel"], async () => { - console.debug("[ns-query] Attempting to add channel to list", channel); - const hasChannelAlready = channels?.some(({ id }) => id === channel?.id); - if (!hasChannelAlready && channel && activeUserNostrProfiles) { - const activeUserNostrProfile = activeUserNostrProfiles[0]; + return useMutation({ + mutationKey: ["chats/add-community-channel"], + mutationFn: async () => { + console.debug("[ns-query] Attempting to add channel to list", channel); + const hasChannelAlready = channels?.some(({ id }) => id === channel?.id); + if (!hasChannelAlready && channel && activeUserNostrProfiles) { + const activeUserNostrProfile = activeUserNostrProfiles[0]; - const lastSeenRecords = activeUserNostrProfile.channelsLastSeenDate ?? {}; - const lastSeenTags = Object.entries(lastSeenRecords).map( - ([channelId, lastSeenTime]) => [ - "lastSeenDate", - channelId, - lastSeenTime.getTime().toString(), - ], - ); - - await updateProfile({ - tags: [["p", publicKey!!], ...lastSeenTags], - eventMetadata: { - ...activeUserNostrProfile, - joinedChannels: [ - ...(activeUserNostrProfile.joinedChannels ?? []), - channel.id, + const lastSeenRecords = + activeUserNostrProfile.channelsLastSeenDate ?? {}; + const lastSeenTags = Object.entries(lastSeenRecords).map( + ([channelId, lastSeenTime]) => [ + "lastSeenDate", + channelId, + lastSeenTime.getTime().toString(), ], - }, - }); - console.debug("[ns-query] Joined channels list updated. Channel added."); - await queryClient.invalidateQueries([ - ["chats/nostr-get-user-profile", publicKey], - ]); - queryClient.setQueryData( - [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], - [ - ...(queryClient.getQueryData([ - ChatQueries.ORIGINAL_JOINED_CHANNELS, - activeUsername, - ]) ?? []), - channel, - ], - ); - queryClient.setQueryData( - [ChatQueries.JOINED_CHANNELS, activeUsername], - [ - ...( - queryClient.getQueryData([ - ChatQueries.JOINED_CHANNELS, + ); + + await updateProfile({ + tags: [["p", publicKey!!], ...lastSeenTags], + eventMetadata: { + ...activeUserNostrProfile, + joinedChannels: [ + ...(activeUserNostrProfile.joinedChannels ?? []), + channel.id, + ], + }, + }); + console.debug( + "[ns-query] Joined channels list updated. Channel added.", + ); + await queryClient.invalidateQueries({ + queryKey: ["chats/nostr-get-user-profile", publicKey], + }); + queryClient.setQueryData( + [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], + [ + ...(queryClient.getQueryData([ + ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername, - ]) ?? [] - ) - // Since We ecency-vision able to add channels to query manually then We have to keep them unique - .filter((ch) => ch.id !== channel.id), - channel, - ], - ); - } + ]) ?? []), + channel, + ], + ); + queryClient.setQueryData( + [ChatQueries.JOINED_CHANNELS, activeUsername], + [ + ...( + queryClient.getQueryData([ + ChatQueries.JOINED_CHANNELS, + activeUsername, + ]) ?? [] + ) + // Since We ecency-vision able to add channels to query manually then We have to keep them unique + .filter((ch) => ch.id !== channel.id), + channel, + ], + ); + } + }, }); } diff --git a/lib/mutations/add-direct-contact.ts b/lib/mutations/add-direct-contact.ts index 9df3846..990e0e3 100644 --- a/lib/mutations/add-direct-contact.ts +++ b/lib/mutations/add-direct-contact.ts @@ -16,9 +16,9 @@ export function useAddDirectContact() { () => {}, ); - return useMutation( - ["chats/add-direct-contact"], - async (contact: DirectContact) => { + return useMutation({ + mutationKey: ["chats/add-direct-contact"], + mutationFn: async (contact: DirectContact) => { console.debug("[ns-query] Attempting adding direct contact", contact); const directContacts = queryClient.getQueryData([ @@ -47,28 +47,26 @@ export function useAddDirectContact() { console.debug("[ns-query] Added direct contact to list", contact); return contact; }, - { - onSuccess: (contact) => { - if (contact) { - queryClient.setQueryData( - [ChatQueries.DIRECT_CONTACTS, activeUsername], - (directContacts) => { - const notExists = directContacts?.every( - (dc) => dc.pubkey !== contact.pubkey, - ); - if (notExists) { - return [...(directContacts ?? []), contact]; - } - return directContacts; - }, - ); + onSuccess: (contact) => { + if (contact) { + queryClient.setQueryData( + [ChatQueries.DIRECT_CONTACTS, activeUsername], + (directContacts) => { + const notExists = directContacts?.every( + (dc) => dc.pubkey !== contact.pubkey, + ); + if (notExists) { + return [...(directContacts ?? []), contact]; + } + return directContacts; + }, + ); - queryClient.setQueryData( - [ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername], - (data) => [...(data ?? []), contact], - ); - } - }, + queryClient.setQueryData( + [ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername], + (data) => [...(data ?? []), contact], + ); + } }, - ); + }); } diff --git a/lib/mutations/create-community-chat.ts b/lib/mutations/create-community-chat.ts index 205fa75..ced66a5 100644 --- a/lib/mutations/create-community-chat.ts +++ b/lib/mutations/create-community-chat.ts @@ -22,9 +22,9 @@ export function useCreateCommunityChat(community: KindOfCommunity) { ); const { mutateAsync: addToEcency } = useAddChannelToEcency(); - return useMutation( - ["chats/create-community-chat"], - async () => { + return useMutation({ + mutationKey: ["chats/create-community-chat"], + mutationFn: async () => { console.debug( "[ns-query] Attempting to create a channel for", community.name, @@ -50,19 +50,17 @@ export function useCreateCommunityChat(community: KindOfCommunity) { return [convertEvent(data), ecencyChannel] as const; }, - { - onSuccess: async ([channel, ecencyChannel]) => { - if (channel) { - queryClient.setQueryData( - [ChatQueries.COMMUNITY_CHANNEL, channel.communityName], - channel, - ); - queryClient.setQueryData( - ["private-api", "get-community-channel", channel.communityName], - ecencyChannel, - ); - } - }, + onSuccess: async ([channel, ecencyChannel]) => { + if (channel) { + queryClient.setQueryData( + [ChatQueries.COMMUNITY_CHANNEL, channel.communityName], + channel, + ); + queryClient.setQueryData( + ["private-api", "get-community-channel", channel.communityName], + ecencyChannel, + ); + } }, - ); + }); } diff --git a/lib/mutations/hide-message-in-channel.ts b/lib/mutations/hide-message-in-channel.ts index 4dd90f7..4c77aca 100644 --- a/lib/mutations/hide-message-in-channel.ts +++ b/lib/mutations/hide-message-in-channel.ts @@ -27,9 +27,9 @@ export function useHideMessageInChannel(channel?: Channel) { () => {}, ); - return useMutation( - ["chats/hide-message-in-channel", channel?.name], - async ({ messageId, reason, status }: Payload) => { + return useMutation({ + mutationKey: ["chats/hide-message-in-channel", channel?.name], + mutationFn: async ({ messageId, reason, status }: Payload) => { await hideMessageRequest.mutateAsync({ eventMetadata: JSON.stringify({ reason: reason ?? "Hidden by community team", @@ -42,19 +42,17 @@ export function useHideMessageInChannel(channel?: Channel) { }); return { messageId, status }; }, - { - onSuccess: async () => { - await queryClient.invalidateQueries([ + onSuccess: async () => { + await queryClient.invalidateQueries({ + queryKey: [ ChatQueries.HIDDEN_CHANNEL_MESSAGES, activeUsername, channel?.id, - ]); - await queryClient.invalidateQueries([ - NostrQueries.PUBLIC_MESSAGES, - activeUsername, - channel?.id, - ]); - }, + ], + }); + await queryClient.invalidateQueries({ + queryKey: [NostrQueries.PUBLIC_MESSAGES, activeUsername, channel?.id], + }); }, - ); + }); } diff --git a/lib/mutations/import-chat-by-keys.ts b/lib/mutations/import-chat-by-keys.ts index 73bde5b..16a0b39 100644 --- a/lib/mutations/import-chat-by-keys.ts +++ b/lib/mutations/import-chat-by-keys.ts @@ -1,7 +1,6 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { EncryptionTools } from "../utils"; -import { useNostrPublishMutation } from "../nostr"; -import { NostrQueries } from "../nostr/queries"; +import { NostrQueries, useNostrPublishMutation } from "../nostr"; import { useContext } from "react"; import { Kind } from "nostr-tools"; import { UploadKeys } from "../types"; @@ -21,25 +20,25 @@ export function useImportChatByKeys( const { activeUsername, storage } = useContext(ChatContext); const { mutateAsync: uploadChatKeys } = useSaveKeys(); - const { mutateAsync: uploadKeys } = useMutation( - ["chats/upload-public-key"], - async (keys: Parameters[1]) => + const { mutateAsync: uploadKeys } = useMutation({ + mutationKey: ["chats/upload-public-key"], + mutationFn: async (keys: Parameters[1]) => uploadChatKeys({ pubkey: keys.pub, iv: keys.iv.toString("base64"), key: keys.priv, meta: meta ?? {}, }), - ); + }); const { mutateAsync: updateProfile } = useNostrPublishMutation( ["chats/update-nostr-profile"], Kind.Metadata, () => {}, ); - return useMutation( - ["chats/import-chat-by-key"], - async ({ ecencyChatKey, pin }: Payload) => { + return useMutation({ + mutationKey: ["chats/import-chat-by-key"], + mutationFn: async ({ ecencyChatKey, pin }: Payload) => { if (!activeUsername) { return; } @@ -98,8 +97,6 @@ export function useImportChatByKeys( }, }); }, - { - onSuccess, - }, - ); + onSuccess, + }); } diff --git a/lib/mutations/join-chat.ts b/lib/mutations/join-chat.ts index 69c26f7..3c7c200 100644 --- a/lib/mutations/join-chat.ts +++ b/lib/mutations/join-chat.ts @@ -33,9 +33,9 @@ export function useJoinChat( ); const { mutateAsync: uploadKeys } = useSaveKeys(); - return useMutation( - ["chat-join-chat"], - async (pin: string) => { + return useMutation({ + mutationKey: ["chat-join-chat"], + mutationFn: async (pin: string) => { const keys = createNoStrAccount(); storage?.setItem("ecency_nostr_pr_" + activeUsername, pin); @@ -71,8 +71,6 @@ export function useJoinChat( }, }); }, - { - onSuccess, - }, - ); + onSuccess, + }); } diff --git a/lib/mutations/leave-community-channel.ts b/lib/mutations/leave-community-channel.ts index a52fe64..05a24da 100644 --- a/lib/mutations/leave-community-channel.ts +++ b/lib/mutations/leave-community-channel.ts @@ -23,51 +23,55 @@ export function useLeaveCommunityChannel(channel?: Channel) { () => {}, ); - return useMutation(["chats/leave-community-channel"], async () => { - console.debug("[ns-query] Attempting to leave channel", channel); - if (channel && activeUserNostrProfiles) { - const activeUserNostrProfile = activeUserNostrProfiles[0]; + return useMutation({ + mutationKey: ["chats/leave-community-channel"], + mutationFn: async () => { + console.debug("[ns-query] Attempting to leave channel", channel); + if (channel && activeUserNostrProfiles) { + const activeUserNostrProfile = activeUserNostrProfiles[0]; - const lastSeenRecords = activeUserNostrProfile.channelsLastSeenDate ?? {}; - const lastSeenTags = Object.entries(lastSeenRecords).map( - ([channelId, lastSeenTime]) => [ - "lastSeenDate", - channelId, - lastSeenTime.getTime().toString(), - ], - ); + const lastSeenRecords = + activeUserNostrProfile.channelsLastSeenDate ?? {}; + const lastSeenTags = Object.entries(lastSeenRecords).map( + ([channelId, lastSeenTime]) => [ + "lastSeenDate", + channelId, + lastSeenTime.getTime().toString(), + ], + ); - await updateProfile({ - tags: [["p", publicKey!!], ...lastSeenTags], - eventMetadata: { - ...activeUserNostrProfile, - joinedChannels: (activeUserNostrProfile.joinedChannels ?? []).filter( - (c) => c !== channel.id, - ), - }, - }); - console.debug("[ns-query] Joined channels list updated. Channel left."); - await queryClient.invalidateQueries([ - ["chats/nostr-get-user-profile", publicKey], - ]); - queryClient.setQueryData( - [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], - ( - queryClient.getQueryData([ - ChatQueries.ORIGINAL_JOINED_CHANNELS, - activeUsername, - ]) ?? [] - ).filter((c) => c.id !== channel.id), - ); - queryClient.setQueryData( - [ChatQueries.JOINED_CHANNELS, activeUsername], - ( - queryClient.getQueryData([ - ChatQueries.JOINED_CHANNELS, - activeUsername, - ]) ?? [] - ).filter((c) => c.id !== channel.id), - ); - } + await updateProfile({ + tags: [["p", publicKey!!], ...lastSeenTags], + eventMetadata: { + ...activeUserNostrProfile, + joinedChannels: ( + activeUserNostrProfile.joinedChannels ?? [] + ).filter((c) => c !== channel.id), + }, + }); + console.debug("[ns-query] Joined channels list updated. Channel left."); + await queryClient.invalidateQueries({ + queryKey: ["chats/nostr-get-user-profile", publicKey], + }); + queryClient.setQueryData( + [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], + ( + queryClient.getQueryData([ + ChatQueries.ORIGINAL_JOINED_CHANNELS, + activeUsername, + ]) ?? [] + ).filter((c) => c.id !== channel.id), + ); + queryClient.setQueryData( + [ChatQueries.JOINED_CHANNELS, activeUsername], + ( + queryClient.getQueryData([ + ChatQueries.JOINED_CHANNELS, + activeUsername, + ]) ?? [] + ).filter((c) => c.id !== channel.id), + ); + } + }, }); } diff --git a/lib/mutations/logout-from-chats.tsx b/lib/mutations/logout-from-chats.tsx index df02fc7..2616ea2 100644 --- a/lib/mutations/logout-from-chats.tsx +++ b/lib/mutations/logout-from-chats.tsx @@ -8,19 +8,28 @@ export function useLogoutFromChats() { const queryClient = useQueryClient(); const { activeUsername, storage } = useContext(ChatContext); - return useMutation(["chats/logout-from-chats"], async () => { - storage?.removeItem("ecency_nostr_pr_" + activeUsername); - queryClient.setQueryData([NostrQueries.PUBLIC_KEY, activeUsername], ""); - queryClient.setQueryData([NostrQueries.PRIVATE_KEY, activeUsername], ""); - queryClient.setQueryData([ChatQueries.JOINED_CHANNELS, activeUsername], []); - queryClient.setQueryData( - [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], - [], - ); - queryClient.setQueryData( - [ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername], - [], - ); - queryClient.setQueryData([ChatQueries.DIRECT_CONTACTS, activeUsername], []); + return useMutation({ + mutationKey: ["chats/logout-from-chats"], + mutationFn: async () => { + storage?.removeItem("ecency_nostr_pr_" + activeUsername); + queryClient.setQueryData([NostrQueries.PUBLIC_KEY, activeUsername], ""); + queryClient.setQueryData([NostrQueries.PRIVATE_KEY, activeUsername], ""); + queryClient.setQueryData( + [ChatQueries.JOINED_CHANNELS, activeUsername], + [], + ); + queryClient.setQueryData( + [ChatQueries.ORIGINAL_JOINED_CHANNELS, activeUsername], + [], + ); + queryClient.setQueryData( + [ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername], + [], + ); + queryClient.setQueryData( + [ChatQueries.DIRECT_CONTACTS, activeUsername], + [], + ); + }, }); } diff --git a/lib/mutations/mute-user-in-channel.ts b/lib/mutations/mute-user-in-channel.ts index 8f1261b..a19875e 100644 --- a/lib/mutations/mute-user-in-channel.ts +++ b/lib/mutations/mute-user-in-channel.ts @@ -26,35 +26,27 @@ export function useMuteUserInChannel(channel?: Channel) { () => {}, ); - return useMutation( - ["chats/mute-user-in-channel", channel?.name], - async ({ pubkey, reason, status }: Payload) => { - await muteUserRequest.mutateAsync( - { - eventMetadata: JSON.stringify({ - reason: reason ?? "Muted by community team", - }), - tags: [ - ["p", pubkey], - ["e", channel!.id, "channel"], - ["status", status.toString()], - ], - }, - { - onSuccess: () => { - queryClient.invalidateQueries([ - NostrQueries.PUBLIC_MESSAGES, - activeUsername, - channel?.id, - ]); - queryClient.invalidateQueries([ - ChatQueries.BLOCKED_USERS, - activeUsername, - channel?.id, - ]); - }, - }, - ); + return useMutation({ + mutationKey: ["chats/mute-user-in-channel", channel?.name], + mutationFn: async ({ pubkey, reason, status }: Payload) => { + await muteUserRequest.mutateAsync({ + eventMetadata: JSON.stringify({ + reason: reason ?? "Muted by community team", + }), + tags: [ + ["p", pubkey], + ["e", channel!.id, "channel"], + ["status", status.toString()], + ], + }); }, - ); + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: [NostrQueries.PUBLIC_MESSAGES, activeUsername, channel?.id], + }); + queryClient.invalidateQueries({ + queryKey: [ChatQueries.BLOCKED_USERS, activeUsername, channel?.id], + }); + }, + }); } diff --git a/lib/mutations/pin-contact.ts b/lib/mutations/pin-contact.ts index 661d73c..f096f25 100644 --- a/lib/mutations/pin-contact.ts +++ b/lib/mutations/pin-contact.ts @@ -17,9 +17,9 @@ export function usePinContact() { () => {}, ); - return useMutation( - ["chats/nostr-update-direct-contacts-pins"], - async ({ + return useMutation({ + mutationKey: ["chats/nostr-update-direct-contacts-pins"], + mutationFn: async ({ contact, pinned, }: { @@ -46,12 +46,10 @@ export function usePinContact() { contact.pinned = pinned; return contact; }, - { - onSuccess: (contact) => { - if (contact) { - updateContactsBasedOnResult(queryClient, activeUsername, contact); - } - }, + onSuccess: (contact) => { + if (contact) { + updateContactsBasedOnResult(queryClient, activeUsername, contact); + } }, - ); + }); } diff --git a/lib/mutations/resend-message.ts b/lib/mutations/resend-message.ts index f46eac9..aa349ec 100644 --- a/lib/mutations/resend-message.ts +++ b/lib/mutations/resend-message.ts @@ -35,9 +35,9 @@ export function useResendMessage( undefined, ); - return useMutation( - ["chats/send-message"], - async (message: Message) => { + return useMutation({ + mutationKey: ["chats/send-message"], + mutationFn: async (message: Message) => { if (!currentChannel && isCommunity(currentContact?.name)) { throw new Error( "[Chat][SendMessage] – provided user is community but channel not found", @@ -52,32 +52,30 @@ export function useResendMessage( throw new Error("[Chat][SendMessage] – no receiver"); } }, - { - onSuccess: (message) => { + onSuccess: (message) => { + MessagesQueryUtil.updateMessageStatusInQuery( + queryClient, + message, + 0, + activeUsername, + currentChannel?.id ?? currentContact?.pubkey, + ); + onSuccess?.(); + }, + onError: async (error: PublishNostrError | Error) => { + if ("event" in error) { + const message = await convertEvent< + Kind.EncryptedDirectMessage | Kind.ChannelMessage + >(error.event, publicKey!!, privateKey!!)!!; + MessagesQueryUtil.updateMessageStatusInQuery( queryClient, message, - 0, + 2, activeUsername, currentChannel?.id ?? currentContact?.pubkey, ); - onSuccess?.(); - }, - onError: async (error: PublishNostrError | Error) => { - if ("event" in error) { - const message = await convertEvent< - Kind.EncryptedDirectMessage | Kind.ChannelMessage - >(error.event, publicKey!!, privateKey!!)!!; - - MessagesQueryUtil.updateMessageStatusInQuery( - queryClient, - message, - 2, - activeUsername, - currentChannel?.id ?? currentContact?.pubkey, - ); - } - }, + } }, - ); + }); } diff --git a/lib/mutations/restore-chat-by-pin.ts b/lib/mutations/restore-chat-by-pin.ts index ea41e37..18685cb 100644 --- a/lib/mutations/restore-chat-by-pin.ts +++ b/lib/mutations/restore-chat-by-pin.ts @@ -20,38 +20,41 @@ export function useRestoreChatByPin() { ); const { mutateAsync: uploadKeys } = useSaveKeys(); - return useMutation(["chats/restore-chat-by-pin"], async (pin: string) => { - if (!pin || !publicKey || !activeUserData) { - throw new Error( - "[Chat][Nostr] – no pin, public key or account information", + return useMutation({ + mutationKey: ["chats/restore-chat-by-pin"], + mutationFn: async (pin: string) => { + if (!pin || !publicKey || !activeUserData) { + throw new Error( + "[Chat][Nostr] – no pin, public key or account information", + ); + } + + const { iv: initialVector, key: privateKey } = keys ?? {}; + + if (!initialVector || !privateKey) { + throw new Error("[Chat][Nostr] – no initial vector or private key"); + } + + const decryptedKey = EncryptionTools.decrypt( + privateKey, + pin, + Buffer.from(initialVector, "base64"), ); - } - - const { iv: initialVector, key: privateKey } = keys ?? {}; - - if (!initialVector || !privateKey) { - throw new Error("[Chat][Nostr] – no initial vector or private key"); - } - - const decryptedKey = EncryptionTools.decrypt( - privateKey, - pin, - Buffer.from(initialVector, "base64"), - ); - queryClient.setQueryData( - [NostrQueries.PRIVATE_KEY, activeUsername], - decryptedKey, - ); - - storage?.setItem("ecency_nostr_pr_" + activeUsername, pin); - - await updateProfile({ - tags: [["p", publicKey]], - eventMetadata: { - name: activeUsername!, - about: "", - picture: "", - }, - }); + queryClient.setQueryData( + [NostrQueries.PRIVATE_KEY, activeUsername], + decryptedKey, + ); + + storage?.setItem("ecency_nostr_pr_" + activeUsername, pin); + + await updateProfile({ + tags: [["p", publicKey]], + eventMetadata: { + name: activeUsername!, + about: "", + picture: "", + }, + }); + }, }); } diff --git a/lib/mutations/send-message.ts b/lib/mutations/send-message.ts index 5a3635d..8815ffd 100644 --- a/lib/mutations/send-message.ts +++ b/lib/mutations/send-message.ts @@ -43,9 +43,9 @@ export function useSendMessage( ); const { mutateAsync: addDirectContact } = useAddDirectContact(); - return useMutation( - ["chats/send-message"], - async ({ forwardedFrom, message, parentMessage }: Payload) => { + return useMutation({ + mutationKey: ["chats/send-message"], + mutationFn: async ({ forwardedFrom, message, parentMessage }: Payload) => { if (!message || message.includes("Uploading")) { throw new Error( "[Chat][SendMessage] – empty message or has uploading file", @@ -80,34 +80,32 @@ export function useSendMessage( throw new Error("[Chat][SendMessage] – no receiver"); } }, - { - onSuccess: ([message, parentMessage]) => { - message.sent = 0; - message.parentMessage = parentMessage; + onSuccess: ([message, parentMessage]) => { + message.sent = 0; + message.parentMessage = parentMessage; - MessagesQueryUtil.pushMessageToQueryData( + MessagesQueryUtil.pushMessageToQueryData( + queryClient, + message, + activeUsername, + currentChannel?.id ?? currentContact?.pubkey, + ); + onSuccess?.(); + }, + onError: async (error: PublishNostrError | Error) => { + if ("event" in error) { + const message = await convertEvent< + Kind.EncryptedDirectMessage | Kind.ChannelMessage + >(error.event, publicKey!!, privateKey!!)!!; + + MessagesQueryUtil.updateMessageStatusInQuery( queryClient, message, + 2, activeUsername, currentChannel?.id ?? currentContact?.pubkey, ); - onSuccess?.(); - }, - onError: async (error: PublishNostrError | Error) => { - if ("event" in error) { - const message = await convertEvent< - Kind.EncryptedDirectMessage | Kind.ChannelMessage - >(error.event, publicKey!!, privateKey!!)!!; - - MessagesQueryUtil.updateMessageStatusInQuery( - queryClient, - message, - 2, - activeUsername, - currentChannel?.id ?? currentContact?.pubkey, - ); - } - }, + } }, - ); + }); } diff --git a/lib/mutations/update-channel-last-seen-date.ts b/lib/mutations/update-channel-last-seen-date.ts index 5983f04..f84e10f 100644 --- a/lib/mutations/update-channel-last-seen-date.ts +++ b/lib/mutations/update-channel-last-seen-date.ts @@ -21,9 +21,9 @@ export function useUpdateChannelLastSeenDate() { () => {}, ); - return useMutation( - ["chats/nostr-update-channel-last-seen-date"], - async ({ + return useMutation({ + mutationKey: ["chats/nostr-update-channel-last-seen-date"], + mutationFn: async ({ channel, lastSeenDate, }: { @@ -63,27 +63,25 @@ export function useUpdateChannelLastSeenDate() { return lastSeenRecords; }, - { - onSuccess: (lastSeenRecords) => { - if (!lastSeenRecords) { - return; - } - queryClient.setQueryData( - ["chats/nostr-get-user-profile", publicKey], - (data) => { - if (!data) { - return data; - } + onSuccess: (lastSeenRecords) => { + if (!lastSeenRecords) { + return; + } + queryClient.setQueryData( + ["chats/nostr-get-user-profile", publicKey], + (data) => { + if (!data) { + return data; + } - return [ - { - ...data[0], - channelsLastSeenDate: lastSeenRecords, - }, - ]; - }, - ); - }, + return [ + { + ...data[0], + channelsLastSeenDate: lastSeenRecords, + }, + ]; + }, + ); }, - ); + }); } diff --git a/lib/mutations/update-community-channel.ts b/lib/mutations/update-community-channel.ts index 530ad31..c2fc420 100644 --- a/lib/mutations/update-community-channel.ts +++ b/lib/mutations/update-community-channel.ts @@ -18,9 +18,9 @@ export function useUpdateCommunityChannel(channel?: Channel) { ); const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery(); - return useMutation( - ["chats/update-community-channel", channel?.communityName], - async (newUpdatedChannel: Channel) => { + return useMutation({ + mutationKey: ["chats/update-community-channel", channel?.communityName], + mutationFn: async (newUpdatedChannel: Channel) => { if (!channel) { return; } @@ -34,23 +34,21 @@ export function useUpdateCommunityChannel(channel?: Channel) { return newUpdatedChannel; }, - { - onSuccess: (updatedChannel) => { - if (!updatedChannel) { - return; - } - - const tempChannels = [...(channels ?? [])]; - const index = tempChannels.findIndex( - (ch) => ch.id === updatedChannel?.id, - ); - tempChannels[index] = updatedChannel; - - queryClient.setQueryData( - [ChatQueries.JOINED_CHANNELS, activeUsername], - tempChannels, - ); - }, + onSuccess: (updatedChannel) => { + if (!updatedChannel) { + return; + } + + const tempChannels = [...(channels ?? [])]; + const index = tempChannels.findIndex( + (ch) => ch.id === updatedChannel?.id, + ); + tempChannels[index] = updatedChannel; + + queryClient.setQueryData( + [ChatQueries.JOINED_CHANNELS, activeUsername], + tempChannels, + ); }, - ); + }); } diff --git a/lib/mutations/update-direct-contacts-last-seen-date.ts b/lib/mutations/update-direct-contacts-last-seen-date.ts index 664d97f..0edda58 100644 --- a/lib/mutations/update-direct-contacts-last-seen-date.ts +++ b/lib/mutations/update-direct-contacts-last-seen-date.ts @@ -17,9 +17,9 @@ export function useUpdateDirectContactsLastSeenDate() { () => {}, ); - return useMutation( - ["chats/nostr-update-direct-contacts-last-seen-date"], - async ({ + return useMutation({ + mutationKey: ["chats/nostr-update-direct-contacts-last-seen-date"], + mutationFn: async ({ contact, lastSeenDate, }: { @@ -50,12 +50,10 @@ export function useUpdateDirectContactsLastSeenDate() { contact.lastSeenDate = lastSeenDate; return contact; }, - { - onSuccess: (contact) => { - if (contact) { - updateContactsBasedOnResult(queryClient, activeUsername, contact); - } - }, + onSuccess: (contact) => { + if (contact) { + updateContactsBasedOnResult(queryClient, activeUsername, contact); + } }, - ); + }); } diff --git a/lib/nostr/core/nostr-fetch-mutation.ts b/lib/nostr/core/nostr-fetch-mutation.ts index 7e46c19..f5cc6ac 100644 --- a/lib/nostr/core/nostr-fetch-mutation.ts +++ b/lib/nostr/core/nostr-fetch-mutation.ts @@ -17,14 +17,14 @@ export function useNostrFetchMutation( const { pool, readRelays } = useContext(NostrContext); const { publicKey } = useKeysQuery(); - return useMutation( - key, - (newFilters?: Filter[]) => { + return useMutation({ + ...options, + mutationKey: key, + mutationFn: (newFilters?: Filter[]) => { return listenWhileFinish(pool, readRelays, [], publicKey!!, [ ...filters, ...(newFilters ?? []), ]); }, - options, - ); + }); } diff --git a/lib/nostr/core/nostr-fetch-query.tsx b/lib/nostr/core/nostr-fetch-query.tsx index 1d4d6d0..43c3d1c 100644 --- a/lib/nostr/core/nostr-fetch-query.tsx +++ b/lib/nostr/core/nostr-fetch-query.tsx @@ -10,14 +10,15 @@ export function useNostrFetchQuery( key: QueryKey, kindsOrFilters: (Kind | Filter)[], dataResolver: (events: Event[]) => DATA | Promise, - queryOptions?: UseQueryOptions, + queryOptions?: Omit, "queryKey" | "queryFn">, ) { const { pool, readRelays } = useContext(NostrContext); const { publicKey } = useKeysQuery(); - return useQuery( - key, - async () => { + return useQuery({ + ...queryOptions, + queryKey: key, + queryFn: async () => { const kinds = kindsOrFilters.every((item) => typeof item === "number") ? (kindsOrFilters as Kind[]) : []; @@ -35,6 +36,5 @@ export function useNostrFetchQuery( ); return dataResolver(events); }, - queryOptions, - ); + }); } diff --git a/lib/nostr/core/nostr-infinite-fetch-query.ts b/lib/nostr/core/nostr-infinite-fetch-query.ts index 657f7ce..7c4465b 100644 --- a/lib/nostr/core/nostr-infinite-fetch-query.ts +++ b/lib/nostr/core/nostr-infinite-fetch-query.ts @@ -1,7 +1,8 @@ import { + DefinedInitialDataInfiniteOptions, + InfiniteData, QueryKey, useInfiniteQuery, - UseInfiniteQueryOptions, } from "@tanstack/react-query"; import { Event, Filter } from "nostr-tools"; import { listenWhileFinish } from "../utils"; @@ -13,15 +14,25 @@ export function useNostrInfiniteFetchQuery( key: QueryKey, filters: Filter[], dataResolver: (events: Event[]) => DATA | Promise, - queryOptions?: UseInfiniteQueryOptions, + queryOptions: Omit< + DefinedInitialDataInfiniteOptions< + DATA, + Error, + InfiniteData, + QueryKey, + number | undefined + >, + "queryKey" | "queryFn" + >, ) { const { pool, readRelays } = useContext(NostrContext); const { publicKey } = useKeysQuery(); // page param is since timestamp - return useInfiniteQuery( - key, - async ({ pageParam }) => { + return useInfiniteQuery({ + ...queryOptions, + queryKey: key, + queryFn: async ({ pageParam }) => { const events = await listenWhileFinish( pool, readRelays, @@ -34,6 +45,5 @@ export function useNostrInfiniteFetchQuery( ); return dataResolver(events); }, - queryOptions, - ); + }); } diff --git a/lib/nostr/core/nostr-publish-mutation.ts b/lib/nostr/core/nostr-publish-mutation.ts index 9b1893d..5207734 100644 --- a/lib/nostr/core/nostr-publish-mutation.ts +++ b/lib/nostr/core/nostr-publish-mutation.ts @@ -47,9 +47,10 @@ export function useNostrPublishMutation( } }); - return useMutation( - key, - ({ eventMetadata, tags }: Payload) => + return useMutation({ + ...options, + mutationKey: key, + mutationFn: ({ eventMetadata, tags }: Payload) => new Promise(async (resolve, reject) => { let signedEvent: Event | null; try { @@ -105,6 +106,5 @@ export function useNostrPublishMutation( // ), // ); }), - options, - ); + }); } diff --git a/lib/nostr/mutations/find-healthy-relay.ts b/lib/nostr/mutations/find-healthy-relay.ts index 2762f7b..21adc57 100644 --- a/lib/nostr/mutations/find-healthy-relay.ts +++ b/lib/nostr/mutations/find-healthy-relay.ts @@ -5,16 +5,19 @@ import { useMutation } from "@tanstack/react-query"; export function useFindHealthyRelayQuery() { const { pool } = useContext(NostrContext); - return useMutation(["chats/nostr-find-healthy-relay"], async (channelId: string) => { - const relays = (pool?.seenOn(channelId) as string[]) ?? []; - for (const relay of relays) { - try { - await pool?.ensureRelay(relay); - return relay; - } catch (e) { - return undefined; + return useMutation({ + mutationKey: ["chats/nostr-find-healthy-relay"], + mutationFn: async (channelId: string) => { + const relays = (pool?.seenOn(channelId) as string[]) ?? []; + for (const relay of relays) { + try { + await pool?.ensureRelay(relay); + return relay; + } catch (e) { + return undefined; + } } - } - return undefined; + return undefined; + }, }); } diff --git a/lib/nostr/mutations/send-direct-message.ts b/lib/nostr/mutations/send-direct-message.ts index 54c4915..9d90080 100644 --- a/lib/nostr/mutations/send-direct-message.ts +++ b/lib/nostr/mutations/send-direct-message.ts @@ -25,9 +25,13 @@ export function useNostrSendDirectMessage( ); const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery(); - return useMutation( - ["chats/send-direct-message"], - async ({ message, forwardedFrom, parentMessageId }: Payload) => { + return useMutation({ + mutationKey: ["chats/send-direct-message"], + mutationFn: async ({ + message, + forwardedFrom, + parentMessageId, + }: Payload) => { if (!publicKey || !privateKey || !destinationPublicKey) { throw new Error( "[Chat][Nostr] – attempting to send direct message with no private, destination or public key", @@ -61,5 +65,5 @@ export function useNostrSendDirectMessage( privateKey, )!!; }, - ); + }); } diff --git a/lib/nostr/mutations/send-public-message.ts b/lib/nostr/mutations/send-public-message.ts index ccc11aa..fb1e0dc 100644 --- a/lib/nostr/mutations/send-public-message.ts +++ b/lib/nostr/mutations/send-public-message.ts @@ -20,9 +20,13 @@ export function useNostrSendPublicMessage(channelId?: string, parent?: string) { ); const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery(); - return useMutation( - ["chats/send-public-message"], - async ({ message, forwardedFrom, parentMessageId }: Payload) => { + return useMutation({ + mutationKey: ["chats/send-public-message"], + mutationFn: async ({ + message, + forwardedFrom, + parentMessageId, + }: Payload) => { const root = parent || channelId; if (!root) { @@ -47,5 +51,5 @@ export function useNostrSendPublicMessage(channelId?: string, parent?: string) { }); return convertEvent(event)!!; }, - ); + }); } diff --git a/lib/nostr/nostr-provider.tsx b/lib/nostr/nostr-provider.tsx index 4f8188f..296a7d9 100644 --- a/lib/nostr/nostr-provider.tsx +++ b/lib/nostr/nostr-provider.tsx @@ -4,7 +4,7 @@ import { NostrContext } from "./nostr-context"; export const RELAYS: Record = { "wss://none.ecency.com": { read: true, write: true }, - "wss://ntwo.ecency.com": { read: true, write: true } + "wss://ntwo.ecency.com": { read: true, write: true }, }; export function NostrProvider({ children }: PropsWithChildren) { diff --git a/lib/nostr/queries/direct-messages-query.ts b/lib/nostr/queries/direct-messages-query.ts index 1492a1d..acbd188 100644 --- a/lib/nostr/queries/direct-messages-query.ts +++ b/lib/nostr/queries/direct-messages-query.ts @@ -49,6 +49,7 @@ export function useDirectMessagesQuery(contact?: DirectContact) { enabled: !!contact?.pubkey && !!activeUsername && !!privateKey && !!publicKey, initialData: { pages: [[]], pageParams: [] }, + initialPageParam: undefined, getNextPageParam: (lastPage) => lastPage?.sort((a, b) => a.created - b.created)?.[0]?.created, refetchOnMount: false, diff --git a/lib/nostr/queries/public-messages-query.ts b/lib/nostr/queries/public-messages-query.ts index f87028b..db4a8e6 100644 --- a/lib/nostr/queries/public-messages-query.ts +++ b/lib/nostr/queries/public-messages-query.ts @@ -100,6 +100,7 @@ export function usePublicMessagesQuery( }, { enabled: !!channel?.id, + initialPageParam: undefined, initialData: { pages: [[]], pageParams: [] }, getNextPageParam: (lastPage) => lastPage?.sort((a, b) => a.created - b.created)?.[0]?.created, diff --git a/package.json b/package.json index 93bf095..9df890d 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,18 @@ { "name": "@ecency/ns-query", "description": "React-query based Nostr protocol SDK for Ecency vision and mobile", - "version": "1.2.6", + "version": "1.2.6-next", "repository": "https://github.com/ecency/ns-query", "author": "ildar.timerbaev ", "license": "MIT", - "main": "dist/index.js", + "main": "index.js", + "module": "dist/index.esm.js", + "exports": { + ".": { + "import": "./dist/index.esm.js", + "require": "./dist/index.js" + } + }, "types": "dist/index.d.ts", "files": [ "/dist" @@ -23,13 +30,13 @@ "vite-plugin-dts": "^3.6.4" }, "peerDependencies": { - "@tanstack/react-query": "^4.29.7", + "@tanstack/react-query": "^5.15.0", "axios": "^0.21.2", "date-fns": "^2.30.0", "react": "^16.8.6" }, "dependencies": { - "@tanstack/react-query": "^4.29.7", + "@tanstack/react-query": "^5.15.0", "axios": "^0.21.2", "date-fns": "^2.30.0", "nostr-tools": "^1.17.0", diff --git a/vite.config.js b/vite.config.js index 9f85b7f..1fcbd9b 100644 --- a/vite.config.js +++ b/vite.config.js @@ -8,11 +8,13 @@ import react from "@vitejs/plugin-react"; export default defineConfig({ build: { target: ["es2015"], + sourcemap: true, + minify: false, lib: { entry: resolve(__dirname, "lib/index.ts"), name: "dist", fileName: "index", - formats: ["cjs"], + formats: ["esm", "cjs"], }, rollupOptions: { external: [