-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconnection-middleware.ts
110 lines (94 loc) · 2.65 KB
/
connection-middleware.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { Middleware } from "redux";
import { StoreState } from "../store";
import {
SetHasAcceptedTermsAction,
SetPageVisibleAction,
ShowChatScreenAction,
ToggleOpenAction,
setStoredMessage,
} from "../ui/ui-reducer";
import { SendMessageAction, sendMessage } from "../messages/message-middleware";
import { setOptions } from "../options/options-reducer";
import { SocketClient } from "@cognigy/socket-client";
import { setConnecting, setReconnectionLimit } from "./connection-reducer";
import { shouldReestablishConnection } from "../../helper/connection-watchdog";
export interface ISendMessageOptions {
/* overrides the displayed text within a chat bubble. useful for e.g. buttons */
label: string;
}
const CONNECT = "CONNECT";
export const connect = () => ({
type: CONNECT as "CONNECT",
});
export type ConnectAction = ReturnType<typeof connect>;
const NETWORK_ON = "NETWORK_ON";
export const announceNetworkOn = () => ({ type: NETWORK_ON as "NETWORK_ON" });
type announceNetworkOnAction = ReturnType<typeof announceNetworkOn>;
// forwards messages to the socket
export const createConnectionMiddleware =
(client: SocketClient): Middleware<object, StoreState> =>
store =>
next =>
(
action:
| ToggleOpenAction
| ConnectAction
| SetHasAcceptedTermsAction
| SendMessageAction
| ShowChatScreenAction
| SetPageVisibleAction
| announceNetworkOnAction,
) => {
switch (action.type) {
case "CONNECT": {
const { storedMessage } = store.getState().ui;
if (!client.connected && !store.getState().connection.connecting) {
store.dispatch(setConnecting(true));
client
.connect()
.then(() => {
// set options
store.dispatch(setConnecting(false));
store.dispatch(setReconnectionLimit(false));
if (storedMessage) {
store.dispatch(
sendMessage(
{ text: storedMessage.text, data: storedMessage.data },
storedMessage.options,
),
);
store.dispatch(setStoredMessage(null));
}
store.dispatch(setOptions(client.socketOptions));
})
.catch(() => {
store.dispatch(setConnecting(false));
});
}
break;
}
case "SHOW_CHAT_SCREEN": {
if (!client.connected) {
store.dispatch(connect());
}
break;
}
case "SEND_MESSAGE": {
store.dispatch(connect());
break;
}
case "SET_PAGE_VISIBLE": {
if (action.visible && shouldReestablishConnection(store.getState())) {
store.dispatch(connect());
}
break;
}
case "NETWORK_ON": {
if (shouldReestablishConnection(store.getState())) {
store.dispatch(connect());
}
break;
}
}
return next(action);
};