docpouch-client 0.8.4 → 0.8.5
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.
- package/dist/index.d.ts +64 -6
- package/dist/index.js +167 -126
- package/package.json +4 -4
- package/src/__tests__/index.test.ts +7 -7
- package/src/index.ts +334 -284
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,61 @@
|
|
|
1
1
|
import type { I_UserEntry, I_UserLogin, I_UserCreation, I_UserUpdate, I_UserDisplay, I_DocumentEntry, I_DataStructure, I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString, I_DocumentType } from "./types.js";
|
|
2
2
|
import { Socket } from "socket.io-client";
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Client for interacting with docPouch API.
|
|
5
|
+
*/
|
|
6
|
+
export default class docPouchClient {
|
|
7
|
+
/**
|
|
8
|
+
* The base URL of the server.
|
|
9
|
+
*
|
|
10
|
+
* @type {string}
|
|
11
|
+
*/
|
|
4
12
|
baseUrl: string;
|
|
5
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Socket.IO socket instance for real-time communication with the server.
|
|
15
|
+
*
|
|
16
|
+
* @type {Socket}
|
|
17
|
+
*/
|
|
6
18
|
socket: Socket;
|
|
19
|
+
/**
|
|
20
|
+
* Callback function to handle socket events.
|
|
21
|
+
*
|
|
22
|
+
* @type {(event: I_EventString, data: I_WsMessage) => void}
|
|
23
|
+
*/
|
|
7
24
|
callbackFunction: ((event: I_EventString, data: I_WsMessage) => void) | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Flag indicating whether real-time synchronization is enabled.
|
|
27
|
+
*
|
|
28
|
+
* @type {boolean}
|
|
29
|
+
*/
|
|
8
30
|
realTimeSync: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Authentication token used to authorize requests.
|
|
33
|
+
*
|
|
34
|
+
* @private
|
|
35
|
+
* @type {string | null}
|
|
36
|
+
*/
|
|
37
|
+
private authToken;
|
|
38
|
+
/**
|
|
39
|
+
* Flag indicating whether a connection attempt is in progress.
|
|
40
|
+
*
|
|
41
|
+
* @private
|
|
42
|
+
* @type {boolean}
|
|
43
|
+
*/
|
|
9
44
|
private connectionInProgress;
|
|
45
|
+
/**
|
|
46
|
+
* Creates an instance of docPouchClient.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} host - The base URL for the server.
|
|
49
|
+
* @param {number} [port=80] - The port number to connect to (default is 80).
|
|
50
|
+
* @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
|
|
51
|
+
*/
|
|
10
52
|
constructor(host: string, port?: number, callback?: (event: I_EventString, data: I_WsMessage) => void);
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Sets the real-time synchronization status.
|
|
55
|
+
*
|
|
56
|
+
* @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
|
|
57
|
+
*/
|
|
58
|
+
setRealTimeSync(newRealTimeSync: boolean): void;
|
|
15
59
|
login(credentials: I_UserLogin): Promise<I_LoginResponse | null>;
|
|
16
60
|
listUsers(): Promise<I_UserEntry[]>;
|
|
17
61
|
updateUser(userID: string, userData: I_UserUpdate): Promise<void>;
|
|
@@ -29,7 +73,21 @@ export default class dbPouchClient {
|
|
|
29
73
|
createType(type: I_DocumentType): Promise<I_DocumentType>;
|
|
30
74
|
removeType(typeID: string): Promise<void>;
|
|
31
75
|
getTypes(): Promise<I_DocumentType[]>;
|
|
76
|
+
updateType(updatedType: I_DocumentType): Promise<void>;
|
|
32
77
|
setToken(token: string | null): void;
|
|
33
78
|
getVersion(): string;
|
|
34
79
|
debugSocketConnection(): void;
|
|
80
|
+
/**
|
|
81
|
+
* Sets up permanent socket listeners for the client.
|
|
82
|
+
*
|
|
83
|
+
* @private
|
|
84
|
+
*/
|
|
85
|
+
private setupPermanentSocketListeners;
|
|
86
|
+
/**
|
|
87
|
+
* Initializes the WebSocket connection with the server.
|
|
88
|
+
*
|
|
89
|
+
* @private
|
|
90
|
+
*/
|
|
91
|
+
private initWebSocket;
|
|
92
|
+
private request;
|
|
35
93
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,40 +1,39 @@
|
|
|
1
1
|
import { io } from "socket.io-client";
|
|
2
2
|
import packetJson from '../package.json';
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Client for interacting with docPouch API.
|
|
5
|
+
*/
|
|
6
|
+
export default class docPouchClient {
|
|
7
|
+
/**
|
|
8
|
+
* Creates an instance of docPouchClient.
|
|
9
|
+
*
|
|
10
|
+
* @param {string} host - The base URL for the server.
|
|
11
|
+
* @param {number} [port=80] - The port number to connect to (default is 80).
|
|
12
|
+
* @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
|
|
13
|
+
*/
|
|
4
14
|
constructor(host, port = 80, callback) {
|
|
5
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Flag indicating whether real-time synchronization is enabled.
|
|
17
|
+
*
|
|
18
|
+
* @type {boolean}
|
|
19
|
+
*/
|
|
6
20
|
this.realTimeSync = false;
|
|
21
|
+
/**
|
|
22
|
+
* Authentication token used to authorize requests.
|
|
23
|
+
*
|
|
24
|
+
* @private
|
|
25
|
+
* @type {string | null}
|
|
26
|
+
*/
|
|
27
|
+
this.authToken = null;
|
|
28
|
+
/**
|
|
29
|
+
* Flag indicating whether a connection attempt is in progress.
|
|
30
|
+
*
|
|
31
|
+
* @private
|
|
32
|
+
* @type {boolean}
|
|
33
|
+
*/
|
|
7
34
|
this.connectionInProgress = false;
|
|
8
|
-
this.setRealTimeSync = (newRealTimeSync) => {
|
|
9
|
-
console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
|
|
10
|
-
// Skip if the setting isn't changing
|
|
11
|
-
if (newRealTimeSync === this.realTimeSync) {
|
|
12
|
-
console.log("Realtime sync setting unchanged, skipping");
|
|
13
|
-
return;
|
|
14
|
-
}
|
|
15
|
-
this.realTimeSync = newRealTimeSync;
|
|
16
|
-
if (newRealTimeSync && this.authToken) {
|
|
17
|
-
console.log("Activating realtime updates");
|
|
18
|
-
// Ensure we're not in the middle of another connection attempt
|
|
19
|
-
if (this.connectionInProgress) {
|
|
20
|
-
console.log("Connection already in progress, waiting before initializing");
|
|
21
|
-
setTimeout(() => this.initWebSocket(), 500);
|
|
22
|
-
}
|
|
23
|
-
else {
|
|
24
|
-
this.initWebSocket();
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
else if (!newRealTimeSync) {
|
|
28
|
-
console.log("Deactivating realtime updates");
|
|
29
|
-
if (this.socket.connected) {
|
|
30
|
-
console.log("Disconnecting socket");
|
|
31
|
-
this.socket.disconnect();
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
35
|
this.baseUrl = host;
|
|
36
|
-
const socketUrl = host.includes('://') ? host : `
|
|
37
|
-
// Don't append port twice if it's already in the URL
|
|
36
|
+
const socketUrl = host.includes('://') ? host : `https://${host}`;
|
|
38
37
|
const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
|
|
39
38
|
? socketUrl
|
|
40
39
|
: `${socketUrl}:${port}`;
|
|
@@ -54,105 +53,37 @@ export default class dbPouchClient {
|
|
|
54
53
|
this.callbackFunction = callback;
|
|
55
54
|
this.setupPermanentSocketListeners();
|
|
56
55
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
this.socket.on('disconnect', (reason) => {
|
|
68
|
-
console.log('Socket disconnected. Reason:', reason);
|
|
69
|
-
this.connectionInProgress = false;
|
|
70
|
-
});
|
|
71
|
-
this.socket.on('error', (error) => {
|
|
72
|
-
console.error('Socket error:', error);
|
|
73
|
-
this.connectionInProgress = false;
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
initWebSocket() {
|
|
77
|
-
console.log("initWebSocket called. Auth token present:", !!this.authToken, "Connection in progress:", this.connectionInProgress, "Socket connected:", this.socket.connected);
|
|
78
|
-
if (!this.authToken) {
|
|
79
|
-
console.log("Skipping WebSocket initialization: No auth token");
|
|
56
|
+
/**
|
|
57
|
+
* Sets the real-time synchronization status.
|
|
58
|
+
*
|
|
59
|
+
* @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
|
|
60
|
+
*/
|
|
61
|
+
setRealTimeSync(newRealTimeSync) {
|
|
62
|
+
console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
|
|
63
|
+
// Skip if the setting isn't changing
|
|
64
|
+
if (newRealTimeSync === this.realTimeSync) {
|
|
65
|
+
console.log("Realtime sync setting unchanged, skipping");
|
|
80
66
|
return;
|
|
81
67
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
// Update the auth token
|
|
94
|
-
this.socket.auth = { token: this.authToken };
|
|
95
|
-
// Remove any dynamic event listeners that might have been added
|
|
96
|
-
this.socket.offAny();
|
|
97
|
-
// Set up event handler for application events
|
|
98
|
-
this.socket.onAny((event, data) => {
|
|
99
|
-
if (event === "heartbeatPing") {
|
|
100
|
-
console.log("Ping event received:", data);
|
|
101
|
-
this.socket.emit("heartbeatPong", Date.now());
|
|
102
|
-
}
|
|
103
|
-
else if (this.callbackFunction) {
|
|
104
|
-
this.callbackFunction(event, data);
|
|
105
|
-
}
|
|
106
|
-
});
|
|
107
|
-
// Connect to the server
|
|
108
|
-
console.log("Connecting socket with auth token");
|
|
109
|
-
this.socket.connect();
|
|
110
|
-
// Add a timeout to detect if connection is taking too long
|
|
111
|
-
setTimeout(() => {
|
|
112
|
-
if (this.connectionInProgress) {
|
|
113
|
-
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
114
|
-
this.connectionInProgress = false;
|
|
115
|
-
// If we're still not connected after the timeout, try again with polling
|
|
116
|
-
if (!this.socket.connected) {
|
|
117
|
-
console.log("Retrying connection with polling transport");
|
|
118
|
-
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
119
|
-
this.socket.connect();
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
}, 5000);
|
|
123
|
-
}
|
|
124
|
-
catch (error) {
|
|
125
|
-
console.error('Error in initWebSocket:', error);
|
|
126
|
-
this.connectionInProgress = false;
|
|
68
|
+
this.realTimeSync = newRealTimeSync;
|
|
69
|
+
if (newRealTimeSync && this.authToken) {
|
|
70
|
+
console.log("Activating realtime updates");
|
|
71
|
+
// Ensure we're not in the middle of another connection attempt
|
|
72
|
+
if (this.connectionInProgress) {
|
|
73
|
+
console.log("Connection already in progress, waiting before initializing");
|
|
74
|
+
setTimeout(() => this.initWebSocket(), 500);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
this.initWebSocket();
|
|
78
|
+
}
|
|
127
79
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (requiresAuth && this.authToken)
|
|
134
|
-
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
135
|
-
if (this.socket.id)
|
|
136
|
-
headers['X-Socket-ID'] = this.socket.id;
|
|
137
|
-
const options = {
|
|
138
|
-
method,
|
|
139
|
-
headers,
|
|
140
|
-
body: body ? JSON.stringify(body) : undefined
|
|
141
|
-
};
|
|
142
|
-
// Ensure endpoint starts with /
|
|
143
|
-
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
144
|
-
// Ensure baseUrl doesn't end with /
|
|
145
|
-
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
146
|
-
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
147
|
-
console.log(`Making ${method} request to: ${url}`);
|
|
148
|
-
const response = await fetch(url, options);
|
|
149
|
-
if (!response.ok) {
|
|
150
|
-
if (response.status === 401 || response.status === 403) {
|
|
151
|
-
this.authToken = null;
|
|
80
|
+
else if (!newRealTimeSync) {
|
|
81
|
+
console.log("Deactivating realtime updates");
|
|
82
|
+
if (this.socket.connected) {
|
|
83
|
+
console.log("Disconnecting socket");
|
|
84
|
+
this.socket.disconnect();
|
|
152
85
|
}
|
|
153
|
-
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
154
86
|
}
|
|
155
|
-
return await response.json();
|
|
156
87
|
}
|
|
157
88
|
// User Administration Endpoints
|
|
158
89
|
async login(credentials) {
|
|
@@ -210,7 +141,7 @@ export default class dbPouchClient {
|
|
|
210
141
|
}
|
|
211
142
|
// Data Type Endpoints
|
|
212
143
|
async createType(type) {
|
|
213
|
-
return await this.request('/types/write', '
|
|
144
|
+
return await this.request('/types/write', 'PATCH', type);
|
|
214
145
|
}
|
|
215
146
|
async removeType(typeID) {
|
|
216
147
|
return await this.request(`/types/remove/${typeID}`, 'DELETE');
|
|
@@ -218,6 +149,9 @@ export default class dbPouchClient {
|
|
|
218
149
|
async getTypes() {
|
|
219
150
|
return await this.request('/types/list', 'GET');
|
|
220
151
|
}
|
|
152
|
+
async updateType(updatedType) {
|
|
153
|
+
await this.request(`/types/write`, 'PATCH', updatedType);
|
|
154
|
+
}
|
|
221
155
|
setToken(token) {
|
|
222
156
|
console.log("Setting token to:", token ? "***token***" : "null");
|
|
223
157
|
const tokenChanged = this.authToken !== token;
|
|
@@ -264,4 +198,111 @@ export default class dbPouchClient {
|
|
|
264
198
|
this.socket.connect();
|
|
265
199
|
}
|
|
266
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* Sets up permanent socket listeners for the client.
|
|
203
|
+
*
|
|
204
|
+
* @private
|
|
205
|
+
*/
|
|
206
|
+
setupPermanentSocketListeners() {
|
|
207
|
+
// These are permanent listeners that won't be removed
|
|
208
|
+
this.socket.on('connect_error', (error) => {
|
|
209
|
+
console.error('Socket connection error:', error.message);
|
|
210
|
+
this.connectionInProgress = false;
|
|
211
|
+
});
|
|
212
|
+
this.socket.on('connect', () => {
|
|
213
|
+
console.log('Socket connected successfully with ID:', this.socket.id);
|
|
214
|
+
this.connectionInProgress = false;
|
|
215
|
+
});
|
|
216
|
+
this.socket.on('disconnect', (reason) => {
|
|
217
|
+
console.log('Socket disconnected. Reason:', reason);
|
|
218
|
+
this.connectionInProgress = false;
|
|
219
|
+
});
|
|
220
|
+
this.socket.on('error', (error) => {
|
|
221
|
+
console.error('Socket error:', error);
|
|
222
|
+
this.connectionInProgress = false;
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Initializes the WebSocket connection with the server.
|
|
227
|
+
*
|
|
228
|
+
* @private
|
|
229
|
+
*/
|
|
230
|
+
initWebSocket() {
|
|
231
|
+
console.log("initWebSocket called. Auth token present:", !!this.authToken, "Connection in progress:", this.connectionInProgress, "Socket connected:", this.socket.connected);
|
|
232
|
+
if (!this.authToken) {
|
|
233
|
+
console.log("Skipping WebSocket initialization: No auth token");
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (this.connectionInProgress) {
|
|
237
|
+
console.log("Connection already in progress, skipping initialization");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (this.socket.connected) {
|
|
241
|
+
console.log("Socket already connected with ID:", this.socket.id);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
this.connectionInProgress = true;
|
|
245
|
+
try {
|
|
246
|
+
console.log("Setting up WebSocket connection with token");
|
|
247
|
+
// Update the auth token
|
|
248
|
+
this.socket.auth = { token: this.authToken };
|
|
249
|
+
// Remove any dynamic event listeners that might have been added
|
|
250
|
+
this.socket.offAny();
|
|
251
|
+
// Set up event handler for application events
|
|
252
|
+
this.socket.onAny((event, data) => {
|
|
253
|
+
if (event === "heartbeatPing") {
|
|
254
|
+
console.log("Ping event received:", data);
|
|
255
|
+
this.socket.emit("heartbeatPong", Date.now());
|
|
256
|
+
}
|
|
257
|
+
else if (this.callbackFunction) {
|
|
258
|
+
this.callbackFunction(event, data);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
// Connect to the server
|
|
262
|
+
console.log("Connecting socket with auth token");
|
|
263
|
+
this.socket.connect();
|
|
264
|
+
// Add a timeout to detect if connection is taking too long
|
|
265
|
+
setTimeout(() => {
|
|
266
|
+
if (this.connectionInProgress) {
|
|
267
|
+
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
268
|
+
this.connectionInProgress = false;
|
|
269
|
+
// If we're still not connected after the timeout, try again with polling
|
|
270
|
+
if (!this.socket.connected) {
|
|
271
|
+
console.log("Retrying connection with polling transport");
|
|
272
|
+
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
273
|
+
this.socket.connect();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}, 5000);
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
console.error('Error in initWebSocket:', error);
|
|
280
|
+
this.connectionInProgress = false;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async request(endpoint, method, body, requiresAuth = true) {
|
|
284
|
+
const headers = {
|
|
285
|
+
'Content-Type': 'application/json',
|
|
286
|
+
};
|
|
287
|
+
if (requiresAuth && this.authToken)
|
|
288
|
+
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
289
|
+
if (this.socket.id)
|
|
290
|
+
headers['X-Socket-ID'] = this.socket.id;
|
|
291
|
+
const options = {
|
|
292
|
+
method,
|
|
293
|
+
headers,
|
|
294
|
+
body: body ? JSON.stringify(body) : undefined
|
|
295
|
+
};
|
|
296
|
+
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
297
|
+
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
298
|
+
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
299
|
+
const response = await fetch(url, options);
|
|
300
|
+
if (!response.ok) {
|
|
301
|
+
if (response.status === 401 || response.status === 403) {
|
|
302
|
+
this.authToken = null;
|
|
303
|
+
}
|
|
304
|
+
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
305
|
+
}
|
|
306
|
+
return await response.json();
|
|
307
|
+
}
|
|
267
308
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "docpouch-client",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.5",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"exports": {
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
"license": "MIT",
|
|
23
23
|
"description": "A small class to more easily access the docPouch API",
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"@types/jest": "^
|
|
26
|
-
"@types/node": "^24.0.
|
|
27
|
-
"jest": "^30.0.
|
|
25
|
+
"@types/jest": "^30.0.0",
|
|
26
|
+
"@types/node": "^24.0.3",
|
|
27
|
+
"jest": "^30.0.2",
|
|
28
28
|
"ts-jest": "^29.4.0"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import docPouchClient from '../index.js';
|
|
2
2
|
import packetJson from '../../package.json';
|
|
3
3
|
import {
|
|
4
4
|
I_UserLogin,
|
|
@@ -28,7 +28,7 @@ global.fetch = jest.fn();
|
|
|
28
28
|
const mockFetch = global.fetch as jest.Mock;
|
|
29
29
|
|
|
30
30
|
describe('Index Class', () => {
|
|
31
|
-
let index:
|
|
31
|
+
let index: docPouchClient;
|
|
32
32
|
const baseUrl = 'http://example.com';
|
|
33
33
|
|
|
34
34
|
beforeEach(() => {
|
|
@@ -37,7 +37,7 @@ describe('Index Class', () => {
|
|
|
37
37
|
mockFetch.mockClear();
|
|
38
38
|
|
|
39
39
|
// Create a new instance of Index for each test
|
|
40
|
-
index = new
|
|
40
|
+
index = new docPouchClient(baseUrl);
|
|
41
41
|
|
|
42
42
|
// Mock successful fetch response
|
|
43
43
|
mockFetch.mockImplementation(() =>
|
|
@@ -62,7 +62,7 @@ describe('Index Class', () => {
|
|
|
62
62
|
|
|
63
63
|
it('should connect socket and set up event handler when callback is provided', () => {
|
|
64
64
|
const mockCallback = jest.fn();
|
|
65
|
-
const indexWithCallback = new
|
|
65
|
+
const indexWithCallback = new docPouchClient(baseUrl, mockCallback);
|
|
66
66
|
|
|
67
67
|
expect(indexWithCallback.socket.connect).toHaveBeenCalled();
|
|
68
68
|
expect(indexWithCallback.socket.onAny).toHaveBeenCalled();
|
|
@@ -86,7 +86,7 @@ describe('Index Class', () => {
|
|
|
86
86
|
jest.mock('../../package.json', () => ({ version: packetJson.version }), { virtual: true });
|
|
87
87
|
|
|
88
88
|
// We need to re-create the index instance to pick up the mocked package.json
|
|
89
|
-
const newIndex = new
|
|
89
|
+
const newIndex = new docPouchClient(baseUrl);
|
|
90
90
|
expect(newIndex.getVersion()).toBe(packetJson.version);
|
|
91
91
|
});
|
|
92
92
|
});
|
|
@@ -472,7 +472,7 @@ describe('Index Class', () => {
|
|
|
472
472
|
describe('WebSocket functionality', () => {
|
|
473
473
|
it('should connect socket when callback is provided', () => {
|
|
474
474
|
const mockCallback = jest.fn();
|
|
475
|
-
const indexWithCallback = new
|
|
475
|
+
const indexWithCallback = new docPouchClient(baseUrl, mockCallback);
|
|
476
476
|
|
|
477
477
|
// Verify that connect was called
|
|
478
478
|
expect(indexWithCallback.socket.connect).toHaveBeenCalled();
|
|
@@ -480,7 +480,7 @@ describe('Index Class', () => {
|
|
|
480
480
|
|
|
481
481
|
it('should set up event handler when callback is provided', () => {
|
|
482
482
|
const mockCallback = jest.fn();
|
|
483
|
-
const indexWithCallback = new
|
|
483
|
+
const indexWithCallback = new docPouchClient(baseUrl, mockCallback);
|
|
484
484
|
|
|
485
485
|
// Verify that onAny was called
|
|
486
486
|
expect(indexWithCallback.socket.onAny).toHaveBeenCalled();
|
package/src/index.ts
CHANGED
|
@@ -6,342 +6,392 @@ import type {
|
|
|
6
6
|
I_UserDisplay,
|
|
7
7
|
I_DocumentEntry,
|
|
8
8
|
I_DataStructure,
|
|
9
|
-
|
|
9
|
+
I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString, I_DocumentType
|
|
10
10
|
} from "./types.js";
|
|
11
11
|
import {io, Socket} from "socket.io-client";
|
|
12
12
|
import packetJson from '../package.json'
|
|
13
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
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Client for interacting with docPouch API.
|
|
16
|
+
*/
|
|
17
|
+
export default class docPouchClient {
|
|
18
|
+
/**
|
|
19
|
+
* The base URL of the server.
|
|
20
|
+
*
|
|
21
|
+
* @type {string}
|
|
22
|
+
*/
|
|
23
|
+
baseUrl: string;
|
|
24
|
+
/**
|
|
25
|
+
* Socket.IO socket instance for real-time communication with the server.
|
|
26
|
+
*
|
|
27
|
+
* @type {Socket}
|
|
28
|
+
*/
|
|
29
|
+
socket: Socket;
|
|
30
|
+
/**
|
|
31
|
+
* Callback function to handle socket events.
|
|
32
|
+
*
|
|
33
|
+
* @type {(event: I_EventString, data: I_WsMessage) => void}
|
|
34
|
+
*/
|
|
35
|
+
callbackFunction;
|
|
36
|
+
/**
|
|
37
|
+
* Flag indicating whether real-time synchronization is enabled.
|
|
38
|
+
*
|
|
39
|
+
* @type {boolean}
|
|
40
|
+
*/
|
|
41
|
+
realTimeSync: boolean = false;
|
|
42
|
+
/**
|
|
43
|
+
* Authentication token used to authorize requests.
|
|
44
|
+
*
|
|
45
|
+
* @private
|
|
46
|
+
* @type {string | null}
|
|
47
|
+
*/
|
|
48
|
+
private authToken: string | null = null;
|
|
49
|
+
/**
|
|
50
|
+
* Flag indicating whether a connection attempt is in progress.
|
|
51
|
+
*
|
|
52
|
+
* @private
|
|
53
|
+
* @type {boolean}
|
|
54
|
+
*/
|
|
55
|
+
private connectionInProgress = false;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Creates an instance of docPouchClient.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} host - The base URL for the server.
|
|
61
|
+
* @param {number} [port=80] - The port number to connect to (default is 80).
|
|
62
|
+
* @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
|
|
63
|
+
*/
|
|
64
|
+
constructor(host: string, port: number = 80, callback?: (event: I_EventString, data: I_WsMessage) => void) {
|
|
65
|
+
this.baseUrl = host;
|
|
66
|
+
const socketUrl = host.includes('://') ? host : `https://${host}`;
|
|
67
|
+
const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
|
|
68
|
+
? socketUrl
|
|
69
|
+
: `${socketUrl}:${port}`;
|
|
70
|
+
|
|
71
|
+
console.log(`Initializing Socket.IO with URL: ${socketUrlWithPort}, path: /socket.io`);
|
|
72
|
+
|
|
73
|
+
this.socket = io(`${socketUrlWithPort}`, {
|
|
74
|
+
autoConnect: false,
|
|
75
|
+
transports: ['websocket'], // Try websocket only first
|
|
76
|
+
reconnection: true,
|
|
77
|
+
reconnectionAttempts: 5,
|
|
78
|
+
reconnectionDelay: 1000,
|
|
79
|
+
forceNew: true, // Force a new connection
|
|
80
|
+
auth: {
|
|
81
|
+
token: null // Will be set later
|
|
82
|
+
},
|
|
83
|
+
path: '/socket.io'
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
this.callbackFunction = callback;
|
|
87
|
+
|
|
88
|
+
this.setupPermanentSocketListeners();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Sets the real-time synchronization status.
|
|
93
|
+
*
|
|
94
|
+
* @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
|
|
95
|
+
*/
|
|
96
|
+
setRealTimeSync(newRealTimeSync: boolean) {
|
|
97
|
+
console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
|
|
98
|
+
|
|
99
|
+
// Skip if the setting isn't changing
|
|
100
|
+
if (newRealTimeSync === this.realTimeSync) {
|
|
101
|
+
console.log("Realtime sync setting unchanged, skipping");
|
|
102
|
+
return;
|
|
52
103
|
}
|
|
53
104
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
console.error('Socket error:', error);
|
|
73
|
-
this.connectionInProgress = false;
|
|
74
|
-
});
|
|
105
|
+
this.realTimeSync = newRealTimeSync;
|
|
106
|
+
|
|
107
|
+
if (newRealTimeSync && this.authToken) {
|
|
108
|
+
console.log("Activating realtime updates");
|
|
109
|
+
|
|
110
|
+
// Ensure we're not in the middle of another connection attempt
|
|
111
|
+
if (this.connectionInProgress) {
|
|
112
|
+
console.log("Connection already in progress, waiting before initializing");
|
|
113
|
+
setTimeout(() => this.initWebSocket(), 500);
|
|
114
|
+
} else {
|
|
115
|
+
this.initWebSocket();
|
|
116
|
+
}
|
|
117
|
+
} else if (!newRealTimeSync) {
|
|
118
|
+
console.log("Deactivating realtime updates");
|
|
119
|
+
if (this.socket.connected) {
|
|
120
|
+
console.log("Disconnecting socket");
|
|
121
|
+
this.socket.disconnect();
|
|
122
|
+
}
|
|
75
123
|
}
|
|
124
|
+
}
|
|
76
125
|
|
|
77
|
-
|
|
78
|
-
|
|
126
|
+
// User Administration Endpoints
|
|
127
|
+
async login(credentials: I_UserLogin): Promise<I_LoginResponse | null> {
|
|
128
|
+
const response = await this.request<I_LoginResponse>('/users/login', 'POST', credentials, false);
|
|
129
|
+
if (response.token) {
|
|
130
|
+
this.authToken = response.token;
|
|
79
131
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
132
|
+
// Reconnect websocket with new token if realtime sync is enabled
|
|
133
|
+
if (this.realTimeSync) {
|
|
134
|
+
this.initWebSocket();
|
|
135
|
+
}
|
|
85
136
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (newRealTimeSync && this.authToken) {
|
|
89
|
-
console.log("Activating realtime updates");
|
|
90
|
-
|
|
91
|
-
// Ensure we're not in the middle of another connection attempt
|
|
92
|
-
if (this.connectionInProgress) {
|
|
93
|
-
console.log("Connection already in progress, waiting before initializing");
|
|
94
|
-
setTimeout(() => this.initWebSocket(), 500);
|
|
95
|
-
} else {
|
|
96
|
-
this.initWebSocket();
|
|
97
|
-
}
|
|
98
|
-
} else if (!newRealTimeSync) {
|
|
99
|
-
console.log("Deactivating realtime updates");
|
|
100
|
-
if (this.socket.connected) {
|
|
101
|
-
console.log("Disconnecting socket");
|
|
102
|
-
this.socket.disconnect();
|
|
103
|
-
}
|
|
104
|
-
}
|
|
137
|
+
return {token: response.token, isAdmin: response.isAdmin};
|
|
105
138
|
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
106
141
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
"Socket connected:", this.socket.connected);
|
|
142
|
+
async listUsers(): Promise<I_UserEntry[]> {
|
|
143
|
+
return await this.request<I_UserEntry[]>('/users/list', 'GET');
|
|
144
|
+
}
|
|
111
145
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
146
|
+
async updateUser(userID: string, userData: I_UserUpdate): Promise<void> {
|
|
147
|
+
await this.request<void>(`/users/update/${userID}`, 'PATCH', userData);
|
|
148
|
+
}
|
|
116
149
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}
|
|
150
|
+
async createUser(userData: I_UserCreation): Promise<I_UserDisplay> {
|
|
151
|
+
return await this.request<I_UserDisplay>('/users/create', 'POST', userData);
|
|
152
|
+
}
|
|
121
153
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
154
|
+
async removeUser(userID: string): Promise<void> {
|
|
155
|
+
await this.request<void>(`/users/remove/${userID}`, 'DELETE');
|
|
156
|
+
}
|
|
126
157
|
|
|
127
|
-
|
|
158
|
+
// Document Management Endpoints
|
|
159
|
+
async createDocument(document: I_DocumentEntry): Promise<I_DocumentEntry> {
|
|
160
|
+
return await this.request<I_DocumentEntry>('/docs/create', 'POST', document);
|
|
161
|
+
}
|
|
128
162
|
|
|
129
|
-
|
|
130
|
-
|
|
163
|
+
async listDocuments(): Promise<I_DocumentEntry[]> {
|
|
164
|
+
return await this.request<I_DocumentEntry[]>('/docs/list', 'GET');
|
|
165
|
+
}
|
|
131
166
|
|
|
132
|
-
|
|
133
|
-
|
|
167
|
+
async fetchDocument(queryObject: I_DocumentQuery): Promise<I_DocumentEntry[]> {
|
|
168
|
+
return await this.request<I_DocumentEntry[]>(`/docs/fetch/`, 'POST', queryObject);
|
|
169
|
+
}
|
|
134
170
|
|
|
135
|
-
|
|
136
|
-
|
|
171
|
+
async updateDocument(documentID: string, documentData: I_DocumentEntry): Promise<void> {
|
|
172
|
+
await this.request<void>(`/docs/update/${documentID}`, 'PATCH', documentData);
|
|
173
|
+
}
|
|
137
174
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
console.log("Ping event received:", data);
|
|
142
|
-
this.socket.emit("heartbeatPong", Date.now());
|
|
143
|
-
}
|
|
144
|
-
else if (this.callbackFunction){
|
|
145
|
-
this.callbackFunction(event, data);
|
|
146
|
-
}
|
|
147
|
-
});
|
|
175
|
+
async removeDocument(documentID: string): Promise<void> {
|
|
176
|
+
await this.request<void>(`/docs/remove/${documentID}`, 'DELETE');
|
|
177
|
+
}
|
|
148
178
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
179
|
+
// Data Structure Endpoints
|
|
180
|
+
async createStructure(structure: I_StructureCreation): Promise<I_DataStructure> {
|
|
181
|
+
return await this.request<I_DataStructure>('/structures/create', 'POST', structure);
|
|
182
|
+
}
|
|
152
183
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
157
|
-
this.connectionInProgress = false;
|
|
158
|
-
|
|
159
|
-
// If we're still not connected after the timeout, try again with polling
|
|
160
|
-
if (!this.socket.connected) {
|
|
161
|
-
console.log("Retrying connection with polling transport");
|
|
162
|
-
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
163
|
-
this.socket.connect();
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}, 5000);
|
|
167
|
-
} catch (error) {
|
|
168
|
-
console.error('Error in initWebSocket:', error);
|
|
169
|
-
this.connectionInProgress = false;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
184
|
+
async getStructures(): Promise<I_DataStructure[]> {
|
|
185
|
+
return await this.request<I_DataStructure[]>('/structures/list', 'GET');
|
|
186
|
+
}
|
|
172
187
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
if (requiresAuth && this.authToken)
|
|
179
|
-
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
180
|
-
if (this.socket.id)
|
|
181
|
-
headers['X-Socket-ID'] = this.socket.id;
|
|
182
|
-
|
|
183
|
-
const options: RequestInit = {
|
|
184
|
-
method,
|
|
185
|
-
headers,
|
|
186
|
-
body: body ? JSON.stringify(body) : undefined
|
|
187
|
-
};
|
|
188
|
-
|
|
189
|
-
// Ensure endpoint starts with /
|
|
190
|
-
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
191
|
-
// Ensure baseUrl doesn't end with /
|
|
192
|
-
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
193
|
-
|
|
194
|
-
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
195
|
-
console.log(`Making ${method} request to: ${url}`);
|
|
196
|
-
|
|
197
|
-
const response = await fetch(url, options);
|
|
198
|
-
|
|
199
|
-
if (!response.ok) {
|
|
200
|
-
if (response.status === 401 || response.status === 403) {
|
|
201
|
-
this.authToken = null;
|
|
202
|
-
}
|
|
203
|
-
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
204
|
-
}
|
|
188
|
+
async updateStructure(structureID: string, structureData: I_DataStructure): Promise<void> {
|
|
189
|
+
await this.request<void>(`/structures/update/${structureID}`, 'PATCH', structureData);
|
|
190
|
+
}
|
|
205
191
|
|
|
206
|
-
|
|
207
|
-
}
|
|
192
|
+
async removeStructure(structureID: string): Promise<void> {
|
|
193
|
+
await this.request<void>(`/structures/remove/${structureID}`, 'DELETE');
|
|
194
|
+
}
|
|
208
195
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
this.authToken = response.token;
|
|
196
|
+
// Data Type Endpoints
|
|
197
|
+
async createType(type: I_DocumentType): Promise<I_DocumentType> {
|
|
198
|
+
return await this.request<I_DocumentType>('/types/write', 'PATCH', type);
|
|
199
|
+
}
|
|
214
200
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
201
|
+
async removeType(typeID: string) {
|
|
202
|
+
return await this.request<void>(`/types/remove/${typeID}`, 'DELETE');
|
|
203
|
+
}
|
|
219
204
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
205
|
+
async getTypes(): Promise<I_DocumentType[]> {
|
|
206
|
+
return await this.request<I_DocumentType[]>('/types/list', 'GET');
|
|
207
|
+
}
|
|
224
208
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
209
|
+
async updateType(updatedType: I_DocumentType): Promise<void> {
|
|
210
|
+
await this.request<void>(`/types/write`, 'PATCH', updatedType);
|
|
211
|
+
}
|
|
228
212
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
async createUser(userData: I_UserCreation): Promise<I_UserDisplay> {
|
|
234
|
-
return await this.request<I_UserDisplay>('/users/create', 'POST', userData);
|
|
235
|
-
}
|
|
213
|
+
setToken(token: string | null): void {
|
|
214
|
+
console.log("Setting token to:", token ? "***token***" : "null");
|
|
236
215
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// Document Management Endpoints
|
|
242
|
-
async createDocument(document: I_DocumentEntry): Promise<I_DocumentEntry> {
|
|
243
|
-
return await this.request<I_DocumentEntry>('/docs/create', 'POST', document);
|
|
244
|
-
}
|
|
216
|
+
const tokenChanged = this.authToken !== token;
|
|
217
|
+
this.authToken = token;
|
|
245
218
|
|
|
246
|
-
|
|
247
|
-
|
|
219
|
+
if (!tokenChanged) {
|
|
220
|
+
console.log("Token unchanged, no need to reconnect");
|
|
221
|
+
return;
|
|
248
222
|
}
|
|
249
223
|
|
|
250
|
-
|
|
251
|
-
|
|
224
|
+
// If we have a new token and realtime sync is enabled
|
|
225
|
+
if (token && this.realTimeSync) {
|
|
226
|
+
console.log("New token set, will initialize WebSocket");
|
|
227
|
+
|
|
228
|
+
// Ensure any existing connection is closed first
|
|
229
|
+
if (this.socket.connected) {
|
|
230
|
+
console.log("Disconnecting existing socket before reconnecting with new token");
|
|
231
|
+
this.socket.disconnect();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Wait a moment for the disconnect to complete
|
|
235
|
+
setTimeout(() => {
|
|
236
|
+
console.log("Initializing WebSocket with new token");
|
|
237
|
+
this.initWebSocket();
|
|
238
|
+
}, 300);
|
|
252
239
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
async removeDocument(documentID: string): Promise<void> {
|
|
259
|
-
await this.request<void>(`/docs/remove/${documentID}`, 'DELETE');
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Data Structure Endpoints
|
|
263
|
-
async createStructure(structure: I_StructureCreation): Promise<I_DataStructure> {
|
|
264
|
-
return await this.request<I_DataStructure>('/structures/create', 'POST', structure);
|
|
240
|
+
// If token was cleared or realtime sync is disabled
|
|
241
|
+
else if (this.socket.connected) {
|
|
242
|
+
console.log("Token cleared or realtime sync disabled, disconnecting");
|
|
243
|
+
this.socket.disconnect();
|
|
265
244
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
getVersion() {
|
|
248
|
+
return packetJson.version;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
debugSocketConnection(): void {
|
|
252
|
+
console.log("Socket connection debug info:");
|
|
253
|
+
console.log("- Connected:", this.socket.connected);
|
|
254
|
+
console.log("- Socket ID:", this.socket.id);
|
|
255
|
+
console.log("- Auth token present:", !!this.authToken);
|
|
256
|
+
console.log("- Connection in progress:", this.connectionInProgress);
|
|
257
|
+
console.log("- Realtime sync enabled:", this.realTimeSync);
|
|
258
|
+
console.log("- Socket options:", this.socket.io.opts);
|
|
259
|
+
|
|
260
|
+
// Try to force reconnection
|
|
261
|
+
if (!this.socket.connected && this.authToken && this.realTimeSync) {
|
|
262
|
+
console.log("Attempting to force reconnection...");
|
|
263
|
+
this.socket.auth = {token: this.authToken};
|
|
264
|
+
this.socket.connect();
|
|
269
265
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Sets up permanent socket listeners for the client.
|
|
270
|
+
*
|
|
271
|
+
* @private
|
|
272
|
+
*/
|
|
273
|
+
private setupPermanentSocketListeners() {
|
|
274
|
+
// These are permanent listeners that won't be removed
|
|
275
|
+
this.socket.on('connect_error', (error) => {
|
|
276
|
+
console.error('Socket connection error:', error.message);
|
|
277
|
+
this.connectionInProgress = false;
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
this.socket.on('connect', () => {
|
|
281
|
+
console.log('Socket connected successfully with ID:', this.socket.id);
|
|
282
|
+
this.connectionInProgress = false;
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
this.socket.on('disconnect', (reason) => {
|
|
286
|
+
console.log('Socket disconnected. Reason:', reason);
|
|
287
|
+
this.connectionInProgress = false;
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
this.socket.on('error', (error) => {
|
|
291
|
+
console.error('Socket error:', error);
|
|
292
|
+
this.connectionInProgress = false;
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Initializes the WebSocket connection with the server.
|
|
298
|
+
*
|
|
299
|
+
* @private
|
|
300
|
+
*/
|
|
301
|
+
private initWebSocket() {
|
|
302
|
+
console.log("initWebSocket called. Auth token present:", !!this.authToken,
|
|
303
|
+
"Connection in progress:", this.connectionInProgress,
|
|
304
|
+
"Socket connected:", this.socket.connected);
|
|
305
|
+
|
|
306
|
+
if (!this.authToken) {
|
|
307
|
+
console.log("Skipping WebSocket initialization: No auth token");
|
|
308
|
+
return;
|
|
273
309
|
}
|
|
274
310
|
|
|
275
|
-
|
|
276
|
-
|
|
311
|
+
if (this.connectionInProgress) {
|
|
312
|
+
console.log("Connection already in progress, skipping initialization");
|
|
313
|
+
return;
|
|
277
314
|
}
|
|
278
315
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
316
|
+
if (this.socket.connected) {
|
|
317
|
+
console.log("Socket already connected with ID:", this.socket.id);
|
|
318
|
+
return;
|
|
282
319
|
}
|
|
283
320
|
|
|
284
|
-
|
|
285
|
-
return await this.request<void>(`/types/remove/${typeID}`, 'DELETE');
|
|
286
|
-
}
|
|
321
|
+
this.connectionInProgress = true;
|
|
287
322
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
323
|
+
try {
|
|
324
|
+
console.log("Setting up WebSocket connection with token");
|
|
291
325
|
|
|
292
|
-
|
|
293
|
-
|
|
326
|
+
// Update the auth token
|
|
327
|
+
this.socket.auth = {token: this.authToken};
|
|
294
328
|
|
|
295
|
-
|
|
296
|
-
|
|
329
|
+
// Remove any dynamic event listeners that might have been added
|
|
330
|
+
this.socket.offAny();
|
|
297
331
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
332
|
+
// Set up event handler for application events
|
|
333
|
+
this.socket.onAny((event: I_EventString, data: I_WsMessage) => {
|
|
334
|
+
if (event === "heartbeatPing") {
|
|
335
|
+
console.log("Ping event received:", data);
|
|
336
|
+
this.socket.emit("heartbeatPong", Date.now());
|
|
337
|
+
} else if (this.callbackFunction) {
|
|
338
|
+
this.callbackFunction(event, data);
|
|
301
339
|
}
|
|
340
|
+
});
|
|
302
341
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
// Ensure any existing connection is closed first
|
|
308
|
-
if (this.socket.connected) {
|
|
309
|
-
console.log("Disconnecting existing socket before reconnecting with new token");
|
|
310
|
-
this.socket.disconnect();
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// Wait a moment for the disconnect to complete
|
|
314
|
-
setTimeout(() => {
|
|
315
|
-
console.log("Initializing WebSocket with new token");
|
|
316
|
-
this.initWebSocket();
|
|
317
|
-
}, 300);
|
|
318
|
-
}
|
|
319
|
-
// If token was cleared or realtime sync is disabled
|
|
320
|
-
else if (this.socket.connected) {
|
|
321
|
-
console.log("Token cleared or realtime sync disabled, disconnecting");
|
|
322
|
-
this.socket.disconnect();
|
|
323
|
-
}
|
|
324
|
-
}
|
|
342
|
+
// Connect to the server
|
|
343
|
+
console.log("Connecting socket with auth token");
|
|
344
|
+
this.socket.connect();
|
|
325
345
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
346
|
+
// Add a timeout to detect if connection is taking too long
|
|
347
|
+
setTimeout(() => {
|
|
348
|
+
if (this.connectionInProgress) {
|
|
349
|
+
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
350
|
+
this.connectionInProgress = false;
|
|
329
351
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
console.log("- Auth token present:", !!this.authToken);
|
|
335
|
-
console.log("- Connection in progress:", this.connectionInProgress);
|
|
336
|
-
console.log("- Realtime sync enabled:", this.realTimeSync);
|
|
337
|
-
console.log("- Socket options:", this.socket.io.opts);
|
|
338
|
-
|
|
339
|
-
// Try to force reconnection
|
|
340
|
-
if (!this.socket.connected && this.authToken && this.realTimeSync) {
|
|
341
|
-
console.log("Attempting to force reconnection...");
|
|
342
|
-
this.socket.auth = { token: this.authToken };
|
|
352
|
+
// If we're still not connected after the timeout, try again with polling
|
|
353
|
+
if (!this.socket.connected) {
|
|
354
|
+
console.log("Retrying connection with polling transport");
|
|
355
|
+
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
343
356
|
this.socket.connect();
|
|
357
|
+
}
|
|
344
358
|
}
|
|
359
|
+
}, 5000);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
console.error('Error in initWebSocket:', error);
|
|
362
|
+
this.connectionInProgress = false;
|
|
345
363
|
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private async request<T>(endpoint: string, method: string, body?: any, requiresAuth: boolean = true): Promise<T> {
|
|
367
|
+
const headers: HeadersInit = {
|
|
368
|
+
'Content-Type': 'application/json',
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
if (requiresAuth && this.authToken)
|
|
372
|
+
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
373
|
+
if (this.socket.id)
|
|
374
|
+
headers['X-Socket-ID'] = this.socket.id;
|
|
375
|
+
|
|
376
|
+
const options: RequestInit = {
|
|
377
|
+
method,
|
|
378
|
+
headers,
|
|
379
|
+
body: body ? JSON.stringify(body) : undefined
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
383
|
+
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
384
|
+
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
385
|
+
const response = await fetch(url, options);
|
|
386
|
+
|
|
387
|
+
if (!response.ok) {
|
|
388
|
+
if (response.status === 401 || response.status === 403) {
|
|
389
|
+
this.authToken = null;
|
|
390
|
+
}
|
|
391
|
+
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return await response.json() as T;
|
|
395
|
+
}
|
|
346
396
|
|
|
347
397
|
}
|