Skip to content

Commit 94e6aa8

Browse files
authored
Merge pull request #20 from notificationapi-com/R4js2ANZ/3366-react-sdk-debug-mode
Update version to 0.0.17 and add debug logging functionality to NotificationAPI client SDK
2 parents 9648ae9 + db7f634 commit 94e6aa8

File tree

6 files changed

+171
-19
lines changed

6 files changed

+171
-19
lines changed

lib/api.ts

Lines changed: 55 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { API_REGION } from './interfaces';
2+
import { Logger } from './logger';
23

34
export const api = async (
45
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
@@ -7,27 +8,67 @@ export const api = async (
78
clientId: string,
89
userId: string,
910
hashedUserId?: string,
10-
data?: any
11+
data?: any,
12+
logger?: Logger
1113
): Promise<any> => {
1214
const token = generateBasicTokenForUser(clientId, userId, hashedUserId);
13-
const res = await fetch(
14-
`https://${host}/${clientId}/users/${encodeURIComponent(
15-
userId
16-
)}/${resource}`,
17-
{
15+
const url = `https://${host}/${clientId}/users/${encodeURIComponent(
16+
userId
17+
)}/${resource}`;
18+
19+
const headers = {
20+
Authorization: `Basic ${token}`
21+
};
22+
23+
if (logger) {
24+
logger.log('HTTP Request:', {
25+
method,
26+
host,
27+
url,
28+
body: data
29+
});
30+
}
31+
32+
const startTime = Date.now();
33+
34+
try {
35+
const res = await fetch(url, {
1836
method,
1937
body: JSON.stringify(data),
20-
headers: {
21-
Authorization: `Basic ${token}`
38+
headers
39+
});
40+
41+
if (logger) {
42+
logger.log('HTTP Response:', res);
43+
}
44+
45+
try {
46+
const responseData = await res.json();
47+
48+
if (logger) {
49+
logger.log('Response Data:', responseData);
50+
}
51+
52+
return responseData;
53+
} catch (e) {
54+
if (logger) {
55+
logger.warn('Failed to parse response as JSON:', e);
2256
}
57+
return undefined;
2358
}
24-
);
59+
} catch (error) {
60+
const duration = Date.now() - startTime;
2561

26-
try {
27-
const responseData = await res.json();
28-
return responseData;
29-
} catch (e) {
30-
return undefined;
62+
if (logger) {
63+
logger.error('HTTP Request Failed:', {
64+
error,
65+
url,
66+
headers,
67+
duration: `${duration}ms`
68+
});
69+
}
70+
71+
throw error;
3172
}
3273
};
3374

lib/client.ts

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { api } from './api';
2+
import { Logger } from './logger';
23
import {
34
API_REGION,
45
BaseDeliveryOptions,
@@ -29,6 +30,9 @@ type NotificationAPIClientSDKConfig = {
2930
websocketHost: string | WS_REGION;
3031
keepWebSocketAliveForSeconds: number;
3132
onNewInAppNotifications?: (notifications: InAppNotification[]) => unknown;
33+
34+
// Debug mode:
35+
debug: boolean;
3236
};
3337

3438
const defaultConfig: NotificationAPIClientSDKConfig = {
@@ -42,11 +46,13 @@ const defaultConfig: NotificationAPIClientSDKConfig = {
4246
Date.now() - 30 * 24 * 60 * 60 * 1000
4347
).toISOString(),
4448
onNewInAppNotifications: undefined,
45-
keepWebSocketAliveForSeconds: 24 * 60 * 60 // 24 hours
49+
keepWebSocketAliveForSeconds: 24 * 60 * 60, // 24 hours
50+
debug: false
4651
};
4752

4853
type NotificationAPIClientSDK = {
4954
config: NotificationAPIClientSDKConfig;
55+
logger: Logger;
5056
init(
5157
config: Partial<NotificationAPIClientSDKConfig> & {
5258
userId: string;
@@ -117,22 +123,37 @@ type NotificationAPIClientSDK = {
117123

118124
export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
119125
config: defaultConfig,
126+
logger: new Logger(false),
120127
init: function (config) {
121128
this.config = { ...defaultConfig, ...config };
129+
this.logger = new Logger(this.config.debug);
130+
this.logger.log('Initialized with config:', {
131+
userId: this.config.userId,
132+
clientId: this.config.clientId,
133+
host: this.config.host,
134+
websocketHost: this.config.websocketHost,
135+
debug: this.config.debug,
136+
hasHashedUserId: !!this.config.hashedUserId
137+
});
122138
return {
123139
...this
124140
};
125141
},
126142
rest: {
127143
generic: function (method, resource, data) {
144+
NotificationAPIClientSDK.logger.log(
145+
`API Call: ${method} ${resource}`,
146+
data ? { body: data } : ''
147+
);
128148
return api(
129149
method,
130150
NotificationAPIClientSDK.config.host,
131151
resource,
132152
NotificationAPIClientSDK.config.clientId,
133153
NotificationAPIClientSDK.config.userId,
134154
NotificationAPIClientSDK.config.hashedUserId,
135-
data
155+
data,
156+
NotificationAPIClientSDK.logger
136157
);
137158
},
138159

@@ -177,15 +198,41 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
177198
if (NotificationAPIClientSDK.config.hashedUserId) {
178199
address += `&userIdHash=${encodeURIComponent(NotificationAPIClientSDK.config.hashedUserId)}`;
179200
}
201+
NotificationAPIClientSDK.logger.log('WebSocket connecting to:', address);
180202
NotificationAPIClientSDK.websocket.object = new WebSocket(address);
203+
204+
NotificationAPIClientSDK.websocket.object.onopen = () => {
205+
NotificationAPIClientSDK.logger.log('WebSocket connection opened');
206+
};
207+
208+
NotificationAPIClientSDK.websocket.object.onclose = (event) => {
209+
NotificationAPIClientSDK.logger.log('WebSocket connection closed:', {
210+
code: event.code,
211+
reason: event.reason,
212+
wasClean: event.wasClean
213+
});
214+
};
215+
216+
NotificationAPIClientSDK.websocket.object.onerror = (error) => {
217+
NotificationAPIClientSDK.logger.error('WebSocket error:', error);
218+
};
219+
181220
NotificationAPIClientSDK.websocket.object.onmessage = (m) => {
221+
NotificationAPIClientSDK.logger.log(
222+
'WebSocket message received:',
223+
m.data
224+
);
182225
const body = JSON.parse(m.data);
183226
if (!body || !body.route) {
184227
return;
185228
}
186229

187230
if (body.route === 'inapp_web/new_notifications') {
188231
const message = body as WebSocket_NewNotification_Message;
232+
NotificationAPIClientSDK.logger.log(
233+
'New notifications received:',
234+
message.payload.notifications
235+
);
189236
if (NotificationAPIClientSDK.config.onNewInAppNotifications) {
190237
NotificationAPIClientSDK.config.onNewInAppNotifications(
191238
message.payload.notifications
@@ -197,6 +244,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
197244
},
198245
disconnect: function (callback) {
199246
if (NotificationAPIClientSDK.websocket.object) {
247+
NotificationAPIClientSDK.logger.log('WebSocket disconnecting');
200248
NotificationAPIClientSDK.websocket.object?.close();
201249
if (callback) {
202250
callback(NotificationAPIClientSDK.websocket.object);
@@ -223,17 +271,29 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
223271
// e.g. identify simply maps to postUsers
224272

225273
getInAppNotifications: async (params) => {
274+
NotificationAPIClientSDK.logger.log(
275+
'getInAppNotifications called with params:',
276+
params
277+
);
278+
226279
const maxCountNeeded =
227280
params.maxCountNeeded ||
228281
NotificationAPIClientSDK.config.getInAppDefaultCount;
229282
const oldestNeeded =
230283
params.oldestNeeded ||
231284
NotificationAPIClientSDK.config.getInAppDefaultOldest;
232285

286+
NotificationAPIClientSDK.logger.log('Fetching notifications with:', {
287+
maxCountNeeded,
288+
oldestNeeded,
289+
before: params.before
290+
});
291+
233292
let result: InAppNotification[] = [];
234293
let oldestReceived = params.before;
235294
let hasMore = true;
236295
let shouldLoadMore = true;
296+
237297
while (shouldLoadMore) {
238298
const res = await NotificationAPIClientSDK.rest.getNotifications(
239299
oldestReceived,
@@ -243,6 +303,11 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
243303
const notisWithoutDuplicates = notis.filter(
244304
(n) => !result.find((nn) => nn.id === n.id)
245305
);
306+
307+
NotificationAPIClientSDK.logger.log(
308+
`Received ${notis.length} notifications, ${notisWithoutDuplicates.length} unique`
309+
);
310+
246311
oldestReceived = notisWithoutDuplicates.reduce(
247312
(min: string, n) => (min < n.date ? min : n.date),
248313
params.before
@@ -258,16 +323,34 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
258323
oldestReceived < oldestNeeded
259324
) {
260325
shouldLoadMore = false;
326+
NotificationAPIClientSDK.logger.log('Stopping fetch loop:', {
327+
hasMore,
328+
totalResults: result.length,
329+
maxCountNeeded,
330+
oldestReceived,
331+
oldestNeeded
332+
});
261333
}
262334
}
263335

336+
NotificationAPIClientSDK.logger.log('getInAppNotifications completed:', {
337+
totalItems: result.length,
338+
hasMore,
339+
oldestReceived
340+
});
341+
264342
return {
265343
items: result,
266344
hasMore,
267345
oldestReceived
268346
};
269347
},
270348
updateInAppNotifications: async (params) => {
349+
NotificationAPIClientSDK.logger.log(
350+
'updateInAppNotifications called with params:',
351+
params
352+
);
353+
271354
const body: {
272355
[key: string]: any;
273356
} = {
@@ -290,6 +373,10 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
290373
body.opened = null;
291374
}
292375

376+
NotificationAPIClientSDK.logger.log(
377+
'Updating notifications with body:',
378+
body
379+
);
293380
return NotificationAPIClientSDK.rest.patchNotifications(body);
294381
},
295382
getPreferences: async () => {

lib/logger.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Logger {
2+
constructor(private debug: boolean = false) {}
3+
4+
log(...args: any[]) {
5+
if (this.debug) {
6+
console.log('[NotificationAPI js core SDK Debug]', ...args);
7+
}
8+
}
9+
10+
warn(...args: any[]) {
11+
if (this.debug) {
12+
console.warn('[NotificationAPI js core SDK Debug]', ...args);
13+
}
14+
}
15+
16+
error(...args: any[]) {
17+
if (this.debug) {
18+
console.error('[NotificationAPI js core SDK Debug]', ...args);
19+
}
20+
}
21+
}
22+
23+
export { Logger };

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",

src/main.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { NotificationAPIClientSDK } from '../lib/client';
33
const client = NotificationAPIClientSDK.init({
44
clientId: '24nojpnrsdc53fkslha0roov05',
55
userId: 'sahand',
6+
debug: true,
67

78
// for websocket:
89
onNewInAppNotifications: (notifications) => {

0 commit comments

Comments
 (0)