@churchapps/apphelper 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,247 +1,247 @@
1
- import { ConnectionInterface, SocketActionHandlerInterface, SocketPayloadInterface, ApiHelper, ArrayHelper, CommonEnvironmentHelper } from "@churchapps/helpers";
2
-
3
- export class SocketHelper {
4
- static socket: WebSocket;
5
- static socketId: string;
6
- static actionHandlers: SocketActionHandlerInterface[] = [];
7
- private static personIdChurchId: { personId: string, churchId: string } = { personId: "", churchId: "" };
8
- private static isCleanedUp: boolean = false;
9
-
10
- static setPersonChurch = (pc: { personId: string, churchId: string }) => {
11
-
12
- if (pc?.personId && pc.personId && pc.churchId !== this.personIdChurchId.churchId && pc.personId !== this.personIdChurchId.personId) {
13
- this.personIdChurchId = pc;
14
- this.createAlertConnection();
15
- } else {
16
- }
17
- }
18
-
19
- static createAlertConnection = () => {
20
-
21
- if (SocketHelper.personIdChurchId.personId && SocketHelper.socketId) {
22
- const connection: ConnectionInterface = {
23
- conversationId: "alerts",
24
- churchId: SocketHelper.personIdChurchId.churchId,
25
- displayName: "Test",
26
- socketId: SocketHelper.socketId,
27
- personId: SocketHelper.personIdChurchId.personId
28
- }
29
-
30
-
31
- ApiHelper.postAnonymous("/connections", [connection], "MessagingApi").then((response: any) => {
32
- }).catch((error: any) => {
33
- console.error("❌ Failed to create alert connection:", error);
34
- console.error("❌ Error details:", {
35
- status: error.status,
36
- message: error.message,
37
- response: error.response
38
- });
39
- });
40
- } else {
41
- console.warn('⚠️ SocketHelper: Cannot create alert connection - missing data:', {
42
- hasPersonId: !!SocketHelper.personIdChurchId.personId,
43
- hasSocketId: !!SocketHelper.socketId,
44
- personId: SocketHelper.personIdChurchId.personId,
45
- socketId: SocketHelper.socketId
46
- });
47
- }
48
- }
49
-
50
- static init = async () => {
51
- SocketHelper.cleanup();
52
- SocketHelper.isCleanedUp = false;
53
-
54
- if (SocketHelper.socket && SocketHelper.socket.readyState !== SocketHelper.socket.CLOSED) {
55
- try {
56
- SocketHelper.socket.close();
57
- } catch (e) {
58
- console.error("❌ Error closing existing socket:", e);
59
- }
60
- }
61
-
62
-
63
- await new Promise((resolve, reject) => {
64
- let hasReceivedSocketId = false;
65
- let messageCount = 0;
66
-
67
- try {
68
- SocketHelper.socket = new WebSocket(CommonEnvironmentHelper.MessagingApiSocket);
69
-
70
- SocketHelper.socket.onmessage = (event) => {
71
- if (SocketHelper.isCleanedUp) return;
72
-
73
- messageCount++;
74
-
75
- try {
76
- const payload = JSON.parse(event.data);
77
-
78
- if (payload.action === 'socketId') {
79
- hasReceivedSocketId = true;
80
- }
81
-
82
- // Log all message types we receive
83
- switch (payload.action) {
84
- case 'socketId':
85
- break;
86
- case 'privateMessage':
87
- break;
88
- case 'notification':
89
- break;
90
- case 'message':
91
- break;
92
- case 'reconnect':
93
- break;
94
- default:
95
- }
96
-
97
- SocketHelper.handleMessage(payload);
98
- } catch (error) {
99
- console.error("❌ Error parsing socket message:", error);
100
- console.error("❌ Raw message was:", event.data);
101
- }
102
- };
103
-
104
- SocketHelper.socket.onopen = async (e) => {
105
-
106
- // Send the getId request
107
- SocketHelper.socket.send("getId");
108
-
109
- // Wait longer to see if we get a response
110
- setTimeout(() => {
111
- if (!hasReceivedSocketId) {
112
- console.warn('⚠️ SocketHelper: No socket ID received after 3 seconds');
113
- }
114
- resolve(null);
115
- }, 3000);
116
- };
117
-
118
- SocketHelper.socket.onclose = async (e) => {
119
- // Socket closed
120
- };
121
-
122
- SocketHelper.socket.onerror = (error) => {
123
- console.error('❌ SocketHelper: WebSocket connection error:', error);
124
- console.error('❌ SocketHelper: Messages received before error:', messageCount);
125
- reject(error);
126
- };
127
-
128
- } catch (error) {
129
- console.error('❌ SocketHelper: Error initializing socket:', error);
130
- reject(error);
131
- }
132
- });
133
- }
134
-
135
- static addHandler = (action: string, id: string, handleMessage: (data: any) => void) => {
136
- const existing = ArrayHelper.getOne(SocketHelper.actionHandlers, "id", id);
137
- if (existing !== null) {
138
- existing.handleMessage = handleMessage;
139
- } else {
140
- SocketHelper.actionHandlers.push({ action, id, handleMessage });
141
- }
142
- }
143
-
144
- static removeHandler = (id: string) => {
145
- SocketHelper.actionHandlers = SocketHelper.actionHandlers.filter(handler => handler.id !== id);
146
- }
147
-
148
- static removeHandlersByAction = (action: string) => {
149
- SocketHelper.actionHandlers = SocketHelper.actionHandlers.filter(handler => handler.action !== action);
150
- }
151
-
152
- static clearAllHandlers = () => {
153
- SocketHelper.actionHandlers = [];
154
- }
155
-
156
- static handleMessage = (payload: SocketPayloadInterface) => {
157
- if (SocketHelper.isCleanedUp) return;
158
-
159
- try {
160
-
161
- if (payload.action === "socketId") {
162
- SocketHelper.socketId = payload.data;
163
- SocketHelper.createAlertConnection();
164
- }
165
- else {
166
- const matchingHandlers = ArrayHelper.getAll(SocketHelper.actionHandlers, "action", payload.action);
167
-
168
- matchingHandlers.forEach((handler) => {
169
- try {
170
- handler.handleMessage(payload.data);
171
- } catch (error) {
172
- console.error(`❌ Error in handler ${handler.id}:`, error);
173
- }
174
- });
175
- }
176
- } catch (error) {
177
- console.error("❌ Error handling socket message:", error);
178
- }
179
- }
180
-
181
- static cleanup = () => {
182
- SocketHelper.isCleanedUp = true;
183
-
184
- // Close socket connection
185
- if (SocketHelper.socket && SocketHelper.socket.readyState !== SocketHelper.socket.CLOSED) {
186
- try {
187
- SocketHelper.socket.close();
188
- } catch (error) {
189
- console.error("Error closing socket:", error);
190
- }
191
- }
192
-
193
- // Clear references
194
- SocketHelper.socket = null;
195
- SocketHelper.socketId = null;
196
- SocketHelper.actionHandlers = [];
197
- SocketHelper.personIdChurchId = { personId: "", churchId: "" };
198
- }
199
-
200
- static disconnect = () => {
201
- SocketHelper.cleanup();
202
- }
203
-
204
- static isConnected = (): boolean => {
205
- return SocketHelper.socket && SocketHelper.socket.readyState === SocketHelper.socket.OPEN;
206
- }
207
-
208
- static getConnectionState = (): string => {
209
- if (!SocketHelper.socket) return "UNINITIALIZED";
210
-
211
- switch (SocketHelper.socket.readyState) {
212
- case SocketHelper.socket.CONNECTING:
213
- return "CONNECTING";
214
- case SocketHelper.socket.OPEN:
215
- return "OPEN";
216
- case SocketHelper.socket.CLOSING:
217
- return "CLOSING";
218
- case SocketHelper.socket.CLOSED:
219
- return "CLOSED";
220
- default:
221
- return "UNKNOWN";
222
- }
223
- }
224
-
225
- // Global cleanup on window unload
226
- static setupGlobalCleanup = () => {
227
- if (typeof window !== "undefined") {
228
- const cleanup = () => {
229
- SocketHelper.cleanup();
230
- };
231
-
232
- window.addEventListener("beforeunload", cleanup);
233
- window.addEventListener("unload", cleanup);
234
-
235
- // Also cleanup on page visibility change (when tab is closed)
236
- document.addEventListener("visibilitychange", () => {
237
- if (document.visibilityState === "hidden") {
238
- // Optional: cleanup when tab becomes hidden
239
- // SocketHelper.cleanup();
240
- }
241
- });
242
-
243
- return cleanup;
244
- }
245
- }
246
-
247
- }
1
+ import { ConnectionInterface, SocketActionHandlerInterface, SocketPayloadInterface, ApiHelper, ArrayHelper, CommonEnvironmentHelper } from "@churchapps/helpers";
2
+
3
+ export class SocketHelper {
4
+ static socket: WebSocket;
5
+ static socketId: string;
6
+ static actionHandlers: SocketActionHandlerInterface[] = [];
7
+ private static personIdChurchId: { personId: string, churchId: string } = { personId: "", churchId: "" };
8
+ private static isCleanedUp: boolean = false;
9
+
10
+ static setPersonChurch = (pc: { personId: string, churchId: string }) => {
11
+
12
+ if (pc?.personId && pc.personId && pc.churchId !== this.personIdChurchId.churchId && pc.personId !== this.personIdChurchId.personId) {
13
+ this.personIdChurchId = pc;
14
+ this.createAlertConnection();
15
+ } else {
16
+ }
17
+ }
18
+
19
+ static createAlertConnection = () => {
20
+
21
+ if (SocketHelper.personIdChurchId.personId && SocketHelper.socketId) {
22
+ const connection: ConnectionInterface = {
23
+ conversationId: "alerts",
24
+ churchId: SocketHelper.personIdChurchId.churchId,
25
+ displayName: "Test",
26
+ socketId: SocketHelper.socketId,
27
+ personId: SocketHelper.personIdChurchId.personId
28
+ }
29
+
30
+
31
+ ApiHelper.postAnonymous("/connections", [connection], "MessagingApi").then((response: any) => {
32
+ }).catch((error: any) => {
33
+ console.error("❌ Failed to create alert connection:", error);
34
+ console.error("❌ Error details:", {
35
+ status: error.status,
36
+ message: error.message,
37
+ response: error.response
38
+ });
39
+ });
40
+ } else {
41
+ console.warn('⚠️ SocketHelper: Cannot create alert connection - missing data:', {
42
+ hasPersonId: !!SocketHelper.personIdChurchId.personId,
43
+ hasSocketId: !!SocketHelper.socketId,
44
+ personId: SocketHelper.personIdChurchId.personId,
45
+ socketId: SocketHelper.socketId
46
+ });
47
+ }
48
+ }
49
+
50
+ static init = async () => {
51
+ SocketHelper.cleanup();
52
+ SocketHelper.isCleanedUp = false;
53
+
54
+ if (SocketHelper.socket && SocketHelper.socket.readyState !== SocketHelper.socket.CLOSED) {
55
+ try {
56
+ SocketHelper.socket.close();
57
+ } catch (e) {
58
+ console.error("❌ Error closing existing socket:", e);
59
+ }
60
+ }
61
+
62
+
63
+ await new Promise((resolve, reject) => {
64
+ let hasReceivedSocketId = false;
65
+ let messageCount = 0;
66
+
67
+ try {
68
+ SocketHelper.socket = new WebSocket(CommonEnvironmentHelper.MessagingApiSocket);
69
+
70
+ SocketHelper.socket.onmessage = (event) => {
71
+ if (SocketHelper.isCleanedUp) return;
72
+
73
+ messageCount++;
74
+
75
+ try {
76
+ const payload = JSON.parse(event.data);
77
+
78
+ if (payload.action === 'socketId') {
79
+ hasReceivedSocketId = true;
80
+ }
81
+
82
+ // Log all message types we receive
83
+ switch (payload.action) {
84
+ case 'socketId':
85
+ break;
86
+ case 'privateMessage':
87
+ break;
88
+ case 'notification':
89
+ break;
90
+ case 'message':
91
+ break;
92
+ case 'reconnect':
93
+ break;
94
+ default:
95
+ }
96
+
97
+ SocketHelper.handleMessage(payload);
98
+ } catch (error) {
99
+ console.error("❌ Error parsing socket message:", error);
100
+ console.error("❌ Raw message was:", event.data);
101
+ }
102
+ };
103
+
104
+ SocketHelper.socket.onopen = async (e) => {
105
+
106
+ // Send the getId request
107
+ SocketHelper.socket.send("getId");
108
+
109
+ // Wait longer to see if we get a response
110
+ setTimeout(() => {
111
+ if (!hasReceivedSocketId) {
112
+ console.warn('⚠️ SocketHelper: No socket ID received after 3 seconds');
113
+ }
114
+ resolve(null);
115
+ }, 3000);
116
+ };
117
+
118
+ SocketHelper.socket.onclose = async (e) => {
119
+ // Socket closed
120
+ };
121
+
122
+ SocketHelper.socket.onerror = (error) => {
123
+ console.error('❌ SocketHelper: WebSocket connection error:', error);
124
+ console.error('❌ SocketHelper: Messages received before error:', messageCount);
125
+ reject(error);
126
+ };
127
+
128
+ } catch (error) {
129
+ console.error('❌ SocketHelper: Error initializing socket:', error);
130
+ reject(error);
131
+ }
132
+ });
133
+ }
134
+
135
+ static addHandler = (action: string, id: string, handleMessage: (data: any) => void) => {
136
+ const existing = ArrayHelper.getOne(SocketHelper.actionHandlers, "id", id);
137
+ if (existing !== null) {
138
+ existing.handleMessage = handleMessage;
139
+ } else {
140
+ SocketHelper.actionHandlers.push({ action, id, handleMessage });
141
+ }
142
+ }
143
+
144
+ static removeHandler = (id: string) => {
145
+ SocketHelper.actionHandlers = SocketHelper.actionHandlers.filter(handler => handler.id !== id);
146
+ }
147
+
148
+ static removeHandlersByAction = (action: string) => {
149
+ SocketHelper.actionHandlers = SocketHelper.actionHandlers.filter(handler => handler.action !== action);
150
+ }
151
+
152
+ static clearAllHandlers = () => {
153
+ SocketHelper.actionHandlers = [];
154
+ }
155
+
156
+ static handleMessage = (payload: SocketPayloadInterface) => {
157
+ if (SocketHelper.isCleanedUp) return;
158
+
159
+ try {
160
+
161
+ if (payload.action === "socketId") {
162
+ SocketHelper.socketId = payload.data;
163
+ SocketHelper.createAlertConnection();
164
+ }
165
+ else {
166
+ const matchingHandlers = ArrayHelper.getAll(SocketHelper.actionHandlers, "action", payload.action);
167
+
168
+ matchingHandlers.forEach((handler) => {
169
+ try {
170
+ handler.handleMessage(payload.data);
171
+ } catch (error) {
172
+ console.error(`❌ Error in handler ${handler.id}:`, error);
173
+ }
174
+ });
175
+ }
176
+ } catch (error) {
177
+ console.error("❌ Error handling socket message:", error);
178
+ }
179
+ }
180
+
181
+ static cleanup = () => {
182
+ SocketHelper.isCleanedUp = true;
183
+
184
+ // Close socket connection
185
+ if (SocketHelper.socket && SocketHelper.socket.readyState !== SocketHelper.socket.CLOSED) {
186
+ try {
187
+ SocketHelper.socket.close();
188
+ } catch (error) {
189
+ console.error("Error closing socket:", error);
190
+ }
191
+ }
192
+
193
+ // Clear references
194
+ SocketHelper.socket = null;
195
+ SocketHelper.socketId = null;
196
+ SocketHelper.actionHandlers = [];
197
+ SocketHelper.personIdChurchId = { personId: "", churchId: "" };
198
+ }
199
+
200
+ static disconnect = () => {
201
+ SocketHelper.cleanup();
202
+ }
203
+
204
+ static isConnected = (): boolean => {
205
+ return SocketHelper.socket && SocketHelper.socket.readyState === SocketHelper.socket.OPEN;
206
+ }
207
+
208
+ static getConnectionState = (): string => {
209
+ if (!SocketHelper.socket) return "UNINITIALIZED";
210
+
211
+ switch (SocketHelper.socket.readyState) {
212
+ case SocketHelper.socket.CONNECTING:
213
+ return "CONNECTING";
214
+ case SocketHelper.socket.OPEN:
215
+ return "OPEN";
216
+ case SocketHelper.socket.CLOSING:
217
+ return "CLOSING";
218
+ case SocketHelper.socket.CLOSED:
219
+ return "CLOSED";
220
+ default:
221
+ return "UNKNOWN";
222
+ }
223
+ }
224
+
225
+ // Global cleanup on window unload
226
+ static setupGlobalCleanup = () => {
227
+ if (typeof window !== "undefined") {
228
+ const cleanup = () => {
229
+ SocketHelper.cleanup();
230
+ };
231
+
232
+ window.addEventListener("beforeunload", cleanup);
233
+ window.addEventListener("unload", cleanup);
234
+
235
+ // Also cleanup on page visibility change (when tab is closed)
236
+ document.addEventListener("visibilitychange", () => {
237
+ if (document.visibilityState === "hidden") {
238
+ // Optional: cleanup when tab becomes hidden
239
+ // SocketHelper.cleanup();
240
+ }
241
+ });
242
+
243
+ return cleanup;
244
+ }
245
+ }
246
+
247
+ }