-
Notifications
You must be signed in to change notification settings - Fork 3
/
useChatChanged.js
69 lines (59 loc) 路 1.52 KB
/
useChatChanged.js
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
import gql from 'graphql-tag';
import {
useSubscription,
useApolloClient,
} from '@apollo/react-hooks';
import { CHAT_ADDED, CHAT_UPDATED } from '@/constants';
const GET_CHAT_CACHED = gql`
query GetChatCached {
chatLogs @client {
logs
changeType
sortType
}
}
`;
const CHAT_CHANGED = gql`
subscription ChatChanged($channelId: String!) {
chatChanged(channelId: $channelId) {
id
author {
userId
displayName
}
message
likes
isQuestion
createdAt
}
}
`;
const addOrUpdateChat = (cacheData, chat) => {
const { chatLogs } = cacheData;
const indexOfChat = chatLogs.logs.findIndex(({ id }) => id === chat.id);
const newData = {
chatLogs: {
...chatLogs,
logs: [...chatLogs.logs],
},
};
if (indexOfChat === -1) {
newData.chatLogs.logs.push(chat);
newData.chatLogs.changeType = CHAT_ADDED;
} else {
newData.chatLogs.logs.splice(indexOfChat, 1, chat);
newData.chatLogs.changeType = CHAT_UPDATED;
}
return newData;
};
const useChatChanged = (channelId) => {
const client = useApolloClient();
const published = useSubscription(CHAT_CHANGED, { variables: { channelId } });
const chatChanged = published.data && published.data.chatChanged;
if (!chatChanged) return;
const cacheData = client.readQuery({ query: GET_CHAT_CACHED });
const data = addOrUpdateChat(cacheData, chatChanged);
client.writeQuery({ query: GET_CHAT_CACHED, data });
};
export { GET_CHAT_CACHED };
export default useChatChanged;