Skip to content

Commit 4f3fa50

Browse files
refactor: Update realtime fetch logic and rename functions
1 parent 91d44ff commit 4f3fa50

File tree

11 files changed

+100
-80
lines changed

11 files changed

+100
-80
lines changed

README.md

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,6 @@ function MyComponent() {
246246
markAsReadById(id);
247247
}
248248

249-
function handleDeleteNotification(id) {
250-
deleteById(id);
251-
}
252-
253249
return (
254250
{/* Your component logic */}
255251
);

package-lock.json

Lines changed: 7 additions & 7 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
@@ -78,6 +78,6 @@
7878
],
7979
"dependencies": {
8080
"pubsub-js": "^1.9.4",
81-
"@sirenapp/js-sdk": "^1.0.0"
81+
"@sirenapp/js-sdk": "^1.1.0"
8282
}
8383
}

src/components/sirenInbox.tsx

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const {
2222
TOKEN_VERIFICATION_PENDING,
2323
MAXIMUM_ITEMS_PER_FETCH,
2424
VerificationStatus,
25+
EventType,
2526
errorMap
2627
} = Constants;
2728
const { applyTheme, isNonEmptyArray, updateNotifications } = CommonUtils;
@@ -149,7 +150,7 @@ const SirenInbox = (props: SirenInboxProps): ReactElement => {
149150
}
150151
}, [eventListenerData]);
151152

152-
const handleMarkNotificationsAsViewed = async (newNotifications = notifications) => {
153+
const handleMarkAllAsViewed = async (newNotifications = notifications) => {
153154
const currentTimestamp = new Date().getTime();
154155
const isoString = new Date(currentTimestamp).toISOString();
155156
const response = await markAllAsViewed(
@@ -168,10 +169,10 @@ const SirenInbox = (props: SirenInboxProps): ReactElement => {
168169

169170
// Clean up - stop polling when component unmounts
170171
const cleanUp = () => () => {
171-
siren?.stopRealTimeNotificationFetch();
172+
siren?.stopRealTimeFetch(EventType.NOTIFICATION);
172173
setNotifications([]);
173174
PubSub.unsubscribe(events.NOTIFICATION_LIST_EVENT);
174-
handleMarkNotificationsAsViewed();
175+
handleMarkAllAsViewed();
175176
};
176177

177178
const notificationSubscriber = async (type: string, dataString: string) => {
@@ -183,15 +184,15 @@ const SirenInbox = (props: SirenInboxProps): ReactElement => {
183184
// Initialize Siren SDK and fetch notifications
184185
const initialize = async (): Promise<void> => {
185186
if (siren) {
186-
siren?.stopRealTimeNotificationFetch();
187+
siren?.stopRealTimeFetch(EventType.NOTIFICATION);
187188
const allNotifications = await fetchNotifications(siren, true);
188189
const notificationParams: fetchProps = { size: notificationsPerPage };
189190

190191
if (isNonEmptyArray(allNotifications))
191192
notificationParams.start = allNotifications[0].createdAt;
192193

193194
if (verificationStatus === VerificationStatus.SUCCESS)
194-
siren?.startRealTimeNotificationFetch(notificationParams);
195+
siren?.startRealTimeFetch({eventType: EventType.NOTIFICATION, params: notificationParams});
195196
}
196197
};
197198

@@ -214,7 +215,7 @@ const SirenInbox = (props: SirenInboxProps): ReactElement => {
214215
if (nonEmptyResponse) {
215216
const updatedNotifications = isResetList ? responseData : [...notifications, ...responseData];
216217

217-
isResetList && handleMarkNotificationsAsViewed(updatedNotifications);
218+
isResetList && handleMarkAllAsViewed(updatedNotifications);
218219
setNotifications(updatedNotifications);
219220

220221
return updatedNotifications;
@@ -273,15 +274,15 @@ const SirenInbox = (props: SirenInboxProps): ReactElement => {
273274
setNotifications([]);
274275
setIsLoading(true);
275276

276-
siren?.stopRealTimeNotificationFetch();
277+
siren?.stopRealTimeFetch(EventType.NOTIFICATION);
277278
const allNotifications = (await fetchNotifications(siren, true)) || [];
278279
const notificationParams: fetchProps = { size: notificationsPerPage };
279280

280281
if (isNonEmptyArray(allNotifications))
281282
notificationParams.start = allNotifications[0].createdAt;
282283

283284
if (verificationStatus === VerificationStatus.SUCCESS)
284-
siren?.startRealTimeNotificationFetch(notificationParams);
285+
siren?.startRealTimeFetch({eventType: EventType.NOTIFICATION, params:notificationParams});
285286
} catch (err) {
286287
setIsLoading(false);
287288
setIsError(true);

src/components/sirenInboxIcon.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const {
1414
eventTypes,
1515
events,
1616
defaultStyles,
17+
EventType,
1718
VerificationStatus,
1819
errorMap
1920
} = Constants;
@@ -67,7 +68,7 @@ const SirenInboxIcon = (props: SirenInboxIconProps) => {
6768

6869
// Clean up - stop polling when component unmounts
6970
const cleanUp = () => () => {
70-
siren?.stopRealTimeUnviewedCountFetch();
71+
siren?.stopRealTimeFetch(EventType.UNVIEWED_COUNT);
7172
PubSub.unsubscribe(events.NOTIFICATION_COUNT_EVENT);
7273
seUnviewedCount(0);
7374
};
@@ -102,7 +103,7 @@ const SirenInboxIcon = (props: SirenInboxIconProps) => {
102103
const unViewed: UnviewedCountReturnResponse | null =
103104
await siren.fetchUnviewedNotificationsCount();
104105

105-
siren.startRealTimeUnviewedCountFetch();
106+
siren.startRealTimeFetch({eventType: EventType.UNVIEWED_COUNT});
106107
if (unViewed?.data) seUnviewedCount(unViewed.data?.unviewedCount || 0);
107108
if (unViewed?.error) onError(unViewed?.error);
108109
}

src/components/sirenProvider.tsx

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
NotificationDataType,
88
NotificationsApiResponse,
99
SirenErrorType,
10-
UnviewedCountApiResponse,
10+
UnviewedCountApiResponse
1111
} from '@sirenapp/js-sdk/dist/esm/types';
1212

1313
import type { SirenProviderConfigProps } from '../types';
@@ -17,7 +17,8 @@ import {
1717
eventTypes,
1818
IN_APP_RECIPIENT_UNAUTHENTICATED,
1919
MAXIMUM_RETRY_COUNT,
20-
VerificationStatus
20+
VerificationStatus,
21+
EventType
2122
} from '../utils/constants';
2223
import { useSiren } from '../utils';
2324

@@ -74,10 +75,11 @@ const SirenProvider: React.FC<SirenProvider> = ({ config, children }) => {
7475
let retryCount = 0;
7576

7677
const { markAllAsViewed } = useSiren();
77-
78+
7879
const [siren, setSiren] = useState<Siren | null>(null);
79-
const [verificationStatus, setVerificationStatus] = useState<VerificationStatus>(VerificationStatus.PENDING);
80-
80+
const [verificationStatus, setVerificationStatus] = useState<VerificationStatus>(
81+
VerificationStatus.PENDING
82+
);
8183

8284
useEffect(() => {
8385
if (config?.recipientId && config?.userToken) {
@@ -90,8 +92,8 @@ const SirenProvider: React.FC<SirenProvider> = ({ config, children }) => {
9092
}, [config]);
9193

9294
const stopRealTimeFetch = (): void => {
93-
siren?.stopRealTimeNotificationFetch();
94-
siren?.stopRealTimeUnviewedCountFetch();
95+
siren?.stopRealTimeFetch(EventType.NOTIFICATION);
96+
siren?.stopRealTimeFetch(EventType.UNVIEWED_COUNT);
9597
};
9698

9799
const sendResetDataEvents = () => {
@@ -106,9 +108,17 @@ const SirenProvider: React.FC<SirenProvider> = ({ config, children }) => {
106108
PubSub.publish(events.NOTIFICATION_LIST_EVENT, JSON.stringify(updateNotificationPayload));
107109
};
108110

109-
const onUnViewedCountReceived = (response: UnviewedCountApiResponse): void => {
110-
const totalUnviewed = response?.data?.totalUnviewed;
111+
const onNewNotificationEvent = (responseData: NotificationDataType[]) => {
112+
logger.info(`new notifications : ${JSON.stringify(responseData)}`);
113+
114+
markAllAsViewed(responseData[0].createdAt);
115+
const payload = { newNotifications: responseData, action: eventTypes.NEW_NOTIFICATIONS };
116+
117+
PubSub.publish(events.NOTIFICATION_LIST_EVENT, JSON.stringify(payload));
118+
};
111119

120+
const onTotalUnviewedCountEvent = (response: UnviewedCountApiResponse) => {
121+
const totalUnviewed = response.data?.totalUnviewed;
112122
const payload = {
113123
unviewedCount: totalUnviewed,
114124
action: eventTypes.UPDATE_NOTIFICATIONS_COUNT
@@ -117,25 +127,38 @@ const SirenProvider: React.FC<SirenProvider> = ({ config, children }) => {
117127
PubSub.publish(events.NOTIFICATION_COUNT_EVENT, JSON.stringify(payload));
118128
};
119129

120-
const onNotificationReceived = (response: NotificationsApiResponse): void => {
121-
const responseData: NotificationDataType[] = response?.data || [];
130+
const handleNotificationEvent = (response: NotificationsApiResponse) => {
131+
const responseData = response?.data;
122132

123-
if (isNonEmptyArray(responseData)) {
124-
logger.info(`new notifications : ${JSON.stringify(responseData)}`);
125-
126-
markAllAsViewed(responseData[0].createdAt);
127-
const payload = { newNotifications: response?.data, action: eventTypes.NEW_NOTIFICATIONS };
133+
if (Array.isArray(responseData) && isNonEmptyArray(responseData))
134+
onNewNotificationEvent(responseData);
128135

129-
PubSub.publish(events.NOTIFICATION_LIST_EVENT, JSON.stringify(payload));
130-
}
131136
};
137+
const handleUnviewedCountEvent = (response: UnviewedCountApiResponse) => {
138+
const responseData = response?.data;
132139

140+
if (responseData && 'totalUnviewed' in responseData)
141+
onTotalUnviewedCountEvent(response);
142+
143+
};
144+
const onEventReceive = (
145+
response: NotificationsApiResponse | UnviewedCountApiResponse = {},
146+
eventType: EventType
147+
) => {
148+
switch (eventType) {
149+
case EventType.NOTIFICATION:
150+
handleNotificationEvent(response as NotificationsApiResponse);
151+
break;
152+
case EventType.UNVIEWED_COUNT:
153+
handleUnviewedCountEvent(response as UnviewedCountApiResponse);
154+
break;
155+
}
156+
};
133157
const onStatusChange = (status: VerificationStatus) => {
134158
setVerificationStatus(status);
135159
};
136160

137-
138-
const actionCallbacks = { onUnViewedCountReceived, onNotificationReceived, onStatusChange };
161+
const actionCallbacks = { onEventReceive, onStatusChange };
139162

140163
const getDataParams = () => {
141164
return {

src/utils/constants.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export const COLORS = {
1818
neutralColor: '#232326',
1919
borderColor: '#344054',
2020
dateColor: '#98A2B3',
21-
deleteIcon: '#98A2B3',
21+
deleteIcon: '#D0D5DD',
2222
timerIcon: '#98A2B3',
2323
clearAllIcon: '#D0D5DD',
2424
infiniteLoader: '#F56630'
@@ -58,6 +58,11 @@ export const levelLogFns = {
5858
[LogLevel.ERROR]: console.error
5959
};
6060

61+
export enum EventType {
62+
NOTIFICATION = "NOTIFICATIONS",
63+
UNVIEWED_COUNT = "UNVIEWED_COUNT"
64+
}
65+
6166
export enum eventTypes {
6267
MARK_ITEM_AS_VIEWED = 'MARK_ITEM_AS_VIEWED',
6368
MARK_ITEM_AS_READ = 'MARK_ITEM_AS_READ',

src/utils/sirenHook.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const useSiren = () => {
99
const markAsReadById = async (id: string) => {
1010
if (siren)
1111
if (id?.length > 0) {
12-
const response = await siren?.markNotificationAsReadById(id);
12+
const response = await siren?.markAsReadById(id);
1313

1414
if (response?.data) {
1515
const payload = { id, action: eventTypes.MARK_ITEM_AS_READ };
@@ -27,7 +27,7 @@ const useSiren = () => {
2727

2828
const markAsReadByDate = async (untilDate: string) => {
2929
if (siren && untilDate) {
30-
const response = await siren?.markNotificationsAsReadByDate(untilDate);
30+
const response = await siren?.markAsReadByDate(untilDate);
3131

3232
if (response?.data) {
3333
const payload = { action: eventTypes.MARK_ALL_AS_READ };
@@ -44,7 +44,7 @@ const useSiren = () => {
4444
const deleteById = async (id: string, shouldUpdateList: boolean = true) => {
4545
if (siren)
4646
if (id?.length > 0) {
47-
const response = await siren?.deleteNotificationById(id);
47+
const response = await siren?.deleteById(id);
4848

4949
if (response?.data && shouldUpdateList) {
5050
const payload = { id, action: eventTypes.DELETE_ITEM };
@@ -62,7 +62,7 @@ const useSiren = () => {
6262

6363
const deleteByDate = async (untilDate: string) => {
6464
if (siren && untilDate) {
65-
const response = await siren.deleteNotificationsByDate(untilDate);
65+
const response = await siren.deleteByDate(untilDate);
6666

6767
if (response?.data) {
6868
const payload = { action: eventTypes.DELETE_ALL_ITEM };
@@ -78,7 +78,7 @@ const useSiren = () => {
7878

7979
const markAllAsViewed = async (untilDate: string) => {
8080
if (siren && untilDate) {
81-
const response = await siren?.markNotificationsAsViewed(untilDate);
81+
const response = await siren?.markAllAsViewed(untilDate);
8282

8383
if (response?.data) {
8484
const payload = { unviewedCount: 0, action: eventTypes.UPDATE_NOTIFICATIONS_COUNT };

tests/components/sirenNotificationIcon.test.tsx

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,18 +34,16 @@ describe('SirenInboxIcon', () => {
3434

3535
const notificationIcon = <Image source={require('../../src/assets/bellLight.png')} />;
3636
const mockSiren:Pick<Siren, keyof Siren> = {
37-
markNotificationAsReadById: jest.fn(),
38-
markNotificationsAsReadByDate: jest.fn(),
39-
deleteNotificationById: jest.fn(),
40-
deleteNotificationsByDate: jest.fn(),
41-
markNotificationsAsViewed: jest.fn(),
37+
markAsReadById: jest.fn(),
38+
markAsReadByDate: jest.fn(),
39+
deleteById: jest.fn(),
40+
deleteByDate: jest.fn(),
41+
markAllAsViewed: jest.fn(),
4242
verifyToken: jest.fn(),
4343
fetchUnviewedNotificationsCount: jest.fn(async () => UnviewedCountReturnResponse),
4444
fetchAllNotifications: jest.fn(),
45-
startRealTimeNotificationFetch: jest.fn(),
46-
stopRealTimeNotificationFetch: jest.fn(),
47-
startRealTimeUnviewedCountFetch: jest.fn(),
48-
stopRealTimeUnviewedCountFetch: jest.fn(),
45+
startRealTimeFetch: jest.fn(),
46+
stopRealTimeFetch: jest.fn(),
4947
};
5048

5149
jest.spyOn(sirenProvider, 'useSirenContext').mockReturnValue({

tests/components/sirenProvider.test.tsx

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,14 @@ describe('SirenProvider', () => {
2424
</SirenProvider>
2525
);
2626
const mocErrorFn = jest.fn();
27-
const mockNotificationHandler = jest.fn();
28-
const mockCountHandler = jest.fn();
27+
const mockEventHandler = jest.fn();
2928

3029
const sirenObject = new Siren({
3130
token: 'user-token',
3231
recipientId: 'recipient-id',
3332
onError: mocErrorFn,
3433
actionCallbacks: {
35-
onNotificationReceived: mockNotificationHandler,
36-
onUnViewedCountReceived: mockCountHandler
34+
onEventReceive: mockEventHandler,
3735
}
3836
});
3937

0 commit comments

Comments
 (0)