Skip to content

Commit 86c1fb8

Browse files
committed
Update version to 0.0.17 and add debug logging functionality to NotificationAPI client SDK
- Incremented version in package.json and package-lock.json to 0.0.17. - Introduced a debug mode in the NotificationAPIClientSDK configuration. - Added debug logging for API calls, WebSocket events, and notification fetching processes to enhance traceability and debugging capabilities.
1 parent 9648ae9 commit 86c1fb8

File tree

4 files changed

+190
-17
lines changed

4 files changed

+190
-17
lines changed

lib/api.ts

Lines changed: 62 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,77 @@ export const api = async (
77
clientId: string,
88
userId: string,
99
hashedUserId?: string,
10-
data?: any
10+
data?: any,
11+
debug = false
1112
): Promise<any> => {
1213
const token = generateBasicTokenForUser(clientId, userId, hashedUserId);
13-
const res = await fetch(
14-
`https://${host}/${clientId}/users/${encodeURIComponent(
15-
userId
16-
)}/${resource}`,
17-
{
14+
const url = `https://${host}/${clientId}/users/${encodeURIComponent(
15+
userId
16+
)}/${resource}`;
17+
18+
if (debug) {
19+
console.log('[NotificationAPI js core Debug] HTTP Request:', {
20+
method,
21+
url,
22+
hasBody: !!data,
23+
body: data
24+
});
25+
}
26+
27+
const startTime = Date.now();
28+
29+
try {
30+
const res = await fetch(url, {
1831
method,
1932
body: JSON.stringify(data),
2033
headers: {
2134
Authorization: `Basic ${token}`
2235
}
36+
});
37+
38+
const duration = Date.now() - startTime;
39+
40+
if (debug) {
41+
console.log('[NotificationAPI js core Debug] HTTP Response:', {
42+
status: res.status,
43+
statusText: res.statusText,
44+
duration: `${duration}ms`,
45+
url
46+
});
2347
}
24-
);
2548

26-
try {
27-
const responseData = await res.json();
28-
return responseData;
29-
} catch (e) {
30-
return undefined;
49+
try {
50+
const responseData = await res.json();
51+
52+
if (debug) {
53+
console.log(
54+
'[NotificationAPI js core Debug] Response Data:',
55+
responseData
56+
);
57+
}
58+
59+
return responseData;
60+
} catch (e) {
61+
if (debug) {
62+
console.log(
63+
'[NotificationAPI js core Debug] Failed to parse response as JSON:',
64+
e
65+
);
66+
}
67+
return undefined;
68+
}
69+
} catch (error) {
70+
const duration = Date.now() - startTime;
71+
72+
if (debug) {
73+
console.log('[NotificationAPI js core Debug] HTTP Request Failed:', {
74+
error,
75+
duration: `${duration}ms`,
76+
url
77+
});
78+
}
79+
80+
throw error;
3181
}
3282
};
3383

lib/client.ts

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ type NotificationAPIClientSDKConfig = {
2929
websocketHost: string | WS_REGION;
3030
keepWebSocketAliveForSeconds: number;
3131
onNewInAppNotifications?: (notifications: InAppNotification[]) => unknown;
32+
33+
// Debug mode:
34+
debug: boolean;
35+
};
36+
37+
// Debug logger utility
38+
const debugLog = (config: NotificationAPIClientSDKConfig, ...args: any[]) => {
39+
if (config.debug) {
40+
console.log('[NotificationAPI js core Debug]', ...args);
41+
}
3242
};
3343

3444
const defaultConfig: NotificationAPIClientSDKConfig = {
@@ -42,7 +52,8 @@ const defaultConfig: NotificationAPIClientSDKConfig = {
4252
Date.now() - 30 * 24 * 60 * 60 * 1000
4353
).toISOString(),
4454
onNewInAppNotifications: undefined,
45-
keepWebSocketAliveForSeconds: 24 * 60 * 60 // 24 hours
55+
keepWebSocketAliveForSeconds: 24 * 60 * 60, // 24 hours
56+
debug: false
4657
};
4758

4859
type NotificationAPIClientSDK = {
@@ -119,20 +130,38 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
119130
config: defaultConfig,
120131
init: function (config) {
121132
this.config = { ...defaultConfig, ...config };
133+
debugLog(
134+
this.config,
135+
'NotificationAPI js core SDK initialized with config:',
136+
{
137+
userId: this.config.userId,
138+
clientId: this.config.clientId,
139+
host: this.config.host,
140+
websocketHost: this.config.websocketHost,
141+
debug: this.config.debug,
142+
hasHashedUserId: !!this.config.hashedUserId
143+
}
144+
);
122145
return {
123146
...this
124147
};
125148
},
126149
rest: {
127150
generic: function (method, resource, data) {
151+
debugLog(
152+
NotificationAPIClientSDK.config,
153+
`API Call: ${method} ${resource}`,
154+
data ? { body: data } : ''
155+
);
128156
return api(
129157
method,
130158
NotificationAPIClientSDK.config.host,
131159
resource,
132160
NotificationAPIClientSDK.config.clientId,
133161
NotificationAPIClientSDK.config.userId,
134162
NotificationAPIClientSDK.config.hashedUserId,
135-
data
163+
data,
164+
NotificationAPIClientSDK.config.debug
136165
);
137166
},
138167

@@ -177,15 +206,54 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
177206
if (NotificationAPIClientSDK.config.hashedUserId) {
178207
address += `&userIdHash=${encodeURIComponent(NotificationAPIClientSDK.config.hashedUserId)}`;
179208
}
209+
debugLog(
210+
NotificationAPIClientSDK.config,
211+
'WebSocket connecting to:',
212+
address
213+
);
180214
NotificationAPIClientSDK.websocket.object = new WebSocket(address);
215+
216+
NotificationAPIClientSDK.websocket.object.onopen = () => {
217+
debugLog(
218+
NotificationAPIClientSDK.config,
219+
'WebSocket connection opened'
220+
);
221+
};
222+
223+
NotificationAPIClientSDK.websocket.object.onclose = (event) => {
224+
debugLog(
225+
NotificationAPIClientSDK.config,
226+
'WebSocket connection closed:',
227+
{
228+
code: event.code,
229+
reason: event.reason,
230+
wasClean: event.wasClean
231+
}
232+
);
233+
};
234+
235+
NotificationAPIClientSDK.websocket.object.onerror = (error) => {
236+
debugLog(NotificationAPIClientSDK.config, 'WebSocket error:', error);
237+
};
238+
181239
NotificationAPIClientSDK.websocket.object.onmessage = (m) => {
240+
debugLog(
241+
NotificationAPIClientSDK.config,
242+
'WebSocket message received:',
243+
m.data
244+
);
182245
const body = JSON.parse(m.data);
183246
if (!body || !body.route) {
184247
return;
185248
}
186249

187250
if (body.route === 'inapp_web/new_notifications') {
188251
const message = body as WebSocket_NewNotification_Message;
252+
debugLog(
253+
NotificationAPIClientSDK.config,
254+
'New notifications received:',
255+
message.payload.notifications
256+
);
189257
if (NotificationAPIClientSDK.config.onNewInAppNotifications) {
190258
NotificationAPIClientSDK.config.onNewInAppNotifications(
191259
message.payload.notifications
@@ -197,6 +265,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
197265
},
198266
disconnect: function (callback) {
199267
if (NotificationAPIClientSDK.websocket.object) {
268+
debugLog(NotificationAPIClientSDK.config, 'WebSocket disconnecting');
200269
NotificationAPIClientSDK.websocket.object?.close();
201270
if (callback) {
202271
callback(NotificationAPIClientSDK.websocket.object);
@@ -223,18 +292,38 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
223292
// e.g. identify simply maps to postUsers
224293

225294
getInAppNotifications: async (params) => {
295+
debugLog(
296+
NotificationAPIClientSDK.config,
297+
'getInAppNotifications called with params:',
298+
params
299+
);
300+
226301
const maxCountNeeded =
227302
params.maxCountNeeded ||
228303
NotificationAPIClientSDK.config.getInAppDefaultCount;
229304
const oldestNeeded =
230305
params.oldestNeeded ||
231306
NotificationAPIClientSDK.config.getInAppDefaultOldest;
232307

308+
debugLog(NotificationAPIClientSDK.config, 'Fetching notifications with:', {
309+
maxCountNeeded,
310+
oldestNeeded,
311+
before: params.before
312+
});
313+
233314
let result: InAppNotification[] = [];
234315
let oldestReceived = params.before;
235316
let hasMore = true;
236317
let shouldLoadMore = true;
318+
let fetchCount = 0;
319+
237320
while (shouldLoadMore) {
321+
fetchCount++;
322+
debugLog(NotificationAPIClientSDK.config, `Fetch attempt ${fetchCount}`, {
323+
oldestReceived,
324+
resultCount: result.length
325+
});
326+
238327
const res = await NotificationAPIClientSDK.rest.getNotifications(
239328
oldestReceived,
240329
maxCountNeeded
@@ -243,6 +332,12 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
243332
const notisWithoutDuplicates = notis.filter(
244333
(n) => !result.find((nn) => nn.id === n.id)
245334
);
335+
336+
debugLog(
337+
NotificationAPIClientSDK.config,
338+
`Received ${notis.length} notifications, ${notisWithoutDuplicates.length} unique`
339+
);
340+
246341
oldestReceived = notisWithoutDuplicates.reduce(
247342
(min: string, n) => (min < n.date ? min : n.date),
248343
params.before
@@ -258,16 +353,39 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
258353
oldestReceived < oldestNeeded
259354
) {
260355
shouldLoadMore = false;
356+
debugLog(NotificationAPIClientSDK.config, 'Stopping fetch loop:', {
357+
hasMore,
358+
totalResults: result.length,
359+
maxCountNeeded,
360+
oldestReceived,
361+
oldestNeeded
362+
});
261363
}
262364
}
263365

366+
debugLog(
367+
NotificationAPIClientSDK.config,
368+
'getInAppNotifications completed:',
369+
{
370+
totalItems: result.length,
371+
hasMore,
372+
oldestReceived
373+
}
374+
);
375+
264376
return {
265377
items: result,
266378
hasMore,
267379
oldestReceived
268380
};
269381
},
270382
updateInAppNotifications: async (params) => {
383+
debugLog(
384+
NotificationAPIClientSDK.config,
385+
'updateInAppNotifications called with params:',
386+
params
387+
);
388+
271389
const body: {
272390
[key: string]: any;
273391
} = {
@@ -290,6 +408,11 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
290408
body.opened = null;
291409
}
292410

411+
debugLog(
412+
NotificationAPIClientSDK.config,
413+
'Updating notifications with body:',
414+
body
415+
);
293416
return NotificationAPIClientSDK.rest.patchNotifications(body);
294417
},
295418
getPreferences: async () => {

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@notificationapi/core",
3-
"version": "0.0.16",
3+
"version": "0.0.17",
44
"type": "module",
55
"main": "dist/main.js",
66
"types": "dist/main.d.ts",

0 commit comments

Comments
 (0)