-
Notifications
You must be signed in to change notification settings - Fork 0
/
direct-messages-query.ts
58 lines (53 loc) · 1.88 KB
/
direct-messages-query.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
import { Kind } from "nostr-tools";
import { useContext } from "react";
import { ChatContext } from "../../chat-context-provider";
import { DirectContact, DirectMessage, Message } from "../types";
import { useNostrInfiniteFetchQuery } from "../core/nostr-infinite-fetch-query";
import { NostrQueries } from "./queries";
import { convertEvent } from "../utils/event-converter";
import { useKeysQuery } from "../core";
import { useFindAndAssignParentDirectMessage } from "./use-find-and-assign-parent-direct-message";
export function useDirectMessagesQuery(contact?: DirectContact) {
const { activeUsername } = useContext(ChatContext);
const { privateKey, publicKey } = useKeysQuery();
const findAndAssignParentMessage = useFindAndAssignParentDirectMessage();
return useNostrInfiniteFetchQuery<Message[]>(
[NostrQueries.DIRECT_MESSAGES, activeUsername, contact?.pubkey],
[
{
kinds: [Kind.EncryptedDirectMessage],
"#p": [contact?.pubkey ?? ""],
authors: [publicKey!!],
limit: 25,
},
{
kinds: [Kind.EncryptedDirectMessage],
"#p": [publicKey!!],
authors: [contact?.pubkey ?? ""],
limit: 25,
},
],
async (events) => {
const results: DirectMessage[] = [];
for (const event of events) {
const message = (await convertEvent<Kind.EncryptedDirectMessage>(
event,
publicKey!!,
privateKey!!,
)) as DirectMessage;
results.push(message);
}
await findAndAssignParentMessage(results);
return results;
},
{
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,
},
);
}