Skip to content

Commit 0433b57

Browse files
committed
Refactor logging in NotificationAPI client SDK to use Logger class
- Introduced a Logger class to handle debug, warn, and error logging. - Replaced console logging with Logger methods in api and client modules. - Enhanced logging functionality for API requests, WebSocket events, and notification processes.
1 parent 86c1fb8 commit 0433b57

File tree

4 files changed

+73
-83
lines changed

4 files changed

+73
-83
lines changed

lib/api.ts

Lines changed: 12 additions & 17 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',
@@ -8,15 +9,15 @@ export const api = async (
89
userId: string,
910
hashedUserId?: string,
1011
data?: any,
11-
debug = false
12+
logger?: Logger
1213
): Promise<any> => {
1314
const token = generateBasicTokenForUser(clientId, userId, hashedUserId);
1415
const url = `https://${host}/${clientId}/users/${encodeURIComponent(
1516
userId
1617
)}/${resource}`;
1718

18-
if (debug) {
19-
console.log('[NotificationAPI js core Debug] HTTP Request:', {
19+
if (logger) {
20+
logger.log('HTTP Request:', {
2021
method,
2122
url,
2223
hasBody: !!data,
@@ -37,8 +38,8 @@ export const api = async (
3738

3839
const duration = Date.now() - startTime;
3940

40-
if (debug) {
41-
console.log('[NotificationAPI js core Debug] HTTP Response:', {
41+
if (logger) {
42+
logger.log('HTTP Response:', {
4243
status: res.status,
4344
statusText: res.statusText,
4445
duration: `${duration}ms`,
@@ -49,28 +50,22 @@ export const api = async (
4950
try {
5051
const responseData = await res.json();
5152

52-
if (debug) {
53-
console.log(
54-
'[NotificationAPI js core Debug] Response Data:',
55-
responseData
56-
);
53+
if (logger) {
54+
logger.log('Response Data:', responseData);
5755
}
5856

5957
return responseData;
6058
} catch (e) {
61-
if (debug) {
62-
console.log(
63-
'[NotificationAPI js core Debug] Failed to parse response as JSON:',
64-
e
65-
);
59+
if (logger) {
60+
logger.warn('Failed to parse response as JSON:', e);
6661
}
6762
return undefined;
6863
}
6964
} catch (error) {
7065
const duration = Date.now() - startTime;
7166

72-
if (debug) {
73-
console.log('[NotificationAPI js core Debug] HTTP Request Failed:', {
67+
if (logger) {
68+
logger.error('HTTP Request Failed:', {
7469
error,
7570
duration: `${duration}ms`,
7671
url

lib/client.ts

Lines changed: 37 additions & 66 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,
@@ -34,13 +35,6 @@ type NotificationAPIClientSDKConfig = {
3435
debug: boolean;
3536
};
3637

37-
// Debug logger utility
38-
const debugLog = (config: NotificationAPIClientSDKConfig, ...args: any[]) => {
39-
if (config.debug) {
40-
console.log('[NotificationAPI js core Debug]', ...args);
41-
}
42-
};
43-
4438
const defaultConfig: NotificationAPIClientSDKConfig = {
4539
host: 'api.notificationapi.com',
4640
websocketHost: 'ws.notificationapi.com',
@@ -58,6 +52,7 @@ const defaultConfig: NotificationAPIClientSDKConfig = {
5852

5953
type NotificationAPIClientSDK = {
6054
config: NotificationAPIClientSDKConfig;
55+
logger: Logger;
6156
init(
6257
config: Partial<NotificationAPIClientSDKConfig> & {
6358
userId: string;
@@ -128,28 +123,25 @@ type NotificationAPIClientSDK = {
128123

129124
export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
130125
config: defaultConfig,
126+
logger: new Logger(false),
131127
init: function (config) {
132128
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-
);
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+
});
145138
return {
146139
...this
147140
};
148141
},
149142
rest: {
150143
generic: function (method, resource, data) {
151-
debugLog(
152-
NotificationAPIClientSDK.config,
144+
NotificationAPIClientSDK.logger.log(
153145
`API Call: ${method} ${resource}`,
154146
data ? { body: data } : ''
155147
);
@@ -161,7 +153,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
161153
NotificationAPIClientSDK.config.userId,
162154
NotificationAPIClientSDK.config.hashedUserId,
163155
data,
164-
NotificationAPIClientSDK.config.debug
156+
NotificationAPIClientSDK.logger
165157
);
166158
},
167159

@@ -206,39 +198,27 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
206198
if (NotificationAPIClientSDK.config.hashedUserId) {
207199
address += `&userIdHash=${encodeURIComponent(NotificationAPIClientSDK.config.hashedUserId)}`;
208200
}
209-
debugLog(
210-
NotificationAPIClientSDK.config,
211-
'WebSocket connecting to:',
212-
address
213-
);
201+
NotificationAPIClientSDK.logger.log('WebSocket connecting to:', address);
214202
NotificationAPIClientSDK.websocket.object = new WebSocket(address);
215203

216204
NotificationAPIClientSDK.websocket.object.onopen = () => {
217-
debugLog(
218-
NotificationAPIClientSDK.config,
219-
'WebSocket connection opened'
220-
);
205+
NotificationAPIClientSDK.logger.log('WebSocket connection opened');
221206
};
222207

223208
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-
);
209+
NotificationAPIClientSDK.logger.log('WebSocket connection closed:', {
210+
code: event.code,
211+
reason: event.reason,
212+
wasClean: event.wasClean
213+
});
233214
};
234215

235216
NotificationAPIClientSDK.websocket.object.onerror = (error) => {
236-
debugLog(NotificationAPIClientSDK.config, 'WebSocket error:', error);
217+
NotificationAPIClientSDK.logger.error('WebSocket error:', error);
237218
};
238219

239220
NotificationAPIClientSDK.websocket.object.onmessage = (m) => {
240-
debugLog(
241-
NotificationAPIClientSDK.config,
221+
NotificationAPIClientSDK.logger.log(
242222
'WebSocket message received:',
243223
m.data
244224
);
@@ -249,8 +229,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
249229

250230
if (body.route === 'inapp_web/new_notifications') {
251231
const message = body as WebSocket_NewNotification_Message;
252-
debugLog(
253-
NotificationAPIClientSDK.config,
232+
NotificationAPIClientSDK.logger.log(
254233
'New notifications received:',
255234
message.payload.notifications
256235
);
@@ -265,7 +244,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
265244
},
266245
disconnect: function (callback) {
267246
if (NotificationAPIClientSDK.websocket.object) {
268-
debugLog(NotificationAPIClientSDK.config, 'WebSocket disconnecting');
247+
NotificationAPIClientSDK.logger.log('WebSocket disconnecting');
269248
NotificationAPIClientSDK.websocket.object?.close();
270249
if (callback) {
271250
callback(NotificationAPIClientSDK.websocket.object);
@@ -292,8 +271,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
292271
// e.g. identify simply maps to postUsers
293272

294273
getInAppNotifications: async (params) => {
295-
debugLog(
296-
NotificationAPIClientSDK.config,
274+
NotificationAPIClientSDK.logger.log(
297275
'getInAppNotifications called with params:',
298276
params
299277
);
@@ -305,7 +283,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
305283
params.oldestNeeded ||
306284
NotificationAPIClientSDK.config.getInAppDefaultOldest;
307285

308-
debugLog(NotificationAPIClientSDK.config, 'Fetching notifications with:', {
286+
NotificationAPIClientSDK.logger.log('Fetching notifications with:', {
309287
maxCountNeeded,
310288
oldestNeeded,
311289
before: params.before
@@ -319,7 +297,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
319297

320298
while (shouldLoadMore) {
321299
fetchCount++;
322-
debugLog(NotificationAPIClientSDK.config, `Fetch attempt ${fetchCount}`, {
300+
NotificationAPIClientSDK.logger.log(`Fetch attempt ${fetchCount}`, {
323301
oldestReceived,
324302
resultCount: result.length
325303
});
@@ -333,8 +311,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
333311
(n) => !result.find((nn) => nn.id === n.id)
334312
);
335313

336-
debugLog(
337-
NotificationAPIClientSDK.config,
314+
NotificationAPIClientSDK.logger.log(
338315
`Received ${notis.length} notifications, ${notisWithoutDuplicates.length} unique`
339316
);
340317

@@ -353,7 +330,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
353330
oldestReceived < oldestNeeded
354331
) {
355332
shouldLoadMore = false;
356-
debugLog(NotificationAPIClientSDK.config, 'Stopping fetch loop:', {
333+
NotificationAPIClientSDK.logger.log('Stopping fetch loop:', {
357334
hasMore,
358335
totalResults: result.length,
359336
maxCountNeeded,
@@ -363,15 +340,11 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
363340
}
364341
}
365342

366-
debugLog(
367-
NotificationAPIClientSDK.config,
368-
'getInAppNotifications completed:',
369-
{
370-
totalItems: result.length,
371-
hasMore,
372-
oldestReceived
373-
}
374-
);
343+
NotificationAPIClientSDK.logger.log('getInAppNotifications completed:', {
344+
totalItems: result.length,
345+
hasMore,
346+
oldestReceived
347+
});
375348

376349
return {
377350
items: result,
@@ -380,8 +353,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
380353
};
381354
},
382355
updateInAppNotifications: async (params) => {
383-
debugLog(
384-
NotificationAPIClientSDK.config,
356+
NotificationAPIClientSDK.logger.log(
385357
'updateInAppNotifications called with params:',
386358
params
387359
);
@@ -408,8 +380,7 @@ export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
408380
body.opened = null;
409381
}
410382

411-
debugLog(
412-
NotificationAPIClientSDK.config,
383+
NotificationAPIClientSDK.logger.log(
413384
'Updating notifications with body:',
414385
body
415386
);

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 };

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)