-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-direct-contact.ts
72 lines (66 loc) · 2.44 KB
/
add-direct-contact.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ChatQueries } from "../queries";
import { DirectContact, useNostrPublishMutation } from "../nostr";
import { useContext } from "react";
import { Kind } from "nostr-tools";
import { ChatContext } from "../chat-context-provider";
import { ContactsTagsBuilder } from "../utils";
export function useAddDirectContact() {
const { activeUsername } = useContext(ChatContext);
const queryClient = useQueryClient();
const { mutateAsync: publishDirectContact } = useNostrPublishMutation(
["chats/nostr-publish-direct-contact"],
Kind.Contacts,
() => {},
);
return useMutation({
mutationKey: ["chats/add-direct-contact"],
mutationFn: async (contact: DirectContact) => {
console.debug("[ns-query] Attempting adding direct contact", contact);
const directContacts =
queryClient.getQueryData<DirectContact[]>([
ChatQueries.ORIGINAL_DIRECT_CONTACTS,
activeUsername,
]) ?? [];
const hasInDirectContactsAlready = directContacts.some(
(c) => c.name === contact.name && c.pubkey === contact.pubkey,
);
if (hasInDirectContactsAlready) {
console.debug("[ns-query] Direct contact exists already", contact);
return;
}
await publishDirectContact({
tags: [
...ContactsTagsBuilder.buildContactsTags(directContacts),
...ContactsTagsBuilder.buildLastSeenTags(directContacts, contact),
...ContactsTagsBuilder.buildPinTags(directContacts),
ContactsTagsBuilder.buildContactTag(contact),
ContactsTagsBuilder.buildLastSeenTag(contact),
],
eventMetadata: "",
});
console.debug("[ns-query] Added direct contact to list", contact);
return contact;
},
onSuccess: (contact) => {
if (contact) {
queryClient.setQueryData<DirectContact[]>(
[ChatQueries.DIRECT_CONTACTS, activeUsername],
(directContacts) => {
const notExists = directContacts?.every(
(dc) => dc.pubkey !== contact.pubkey,
);
if (notExists) {
return [...(directContacts ?? []), contact];
}
return directContacts;
},
);
queryClient.setQueryData<DirectContact[]>(
[ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername],
(data) => [...(data ?? []), contact],
);
}
},
});
}