Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file.

### Fixed

## [1.2.4] - 2025-02-13

- Remove verify token api call

## [1.2.1] - 2024-06-24

### Fixed
Expand Down
29 changes: 9 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ const sirenInstance = new Siren({
onEventReceive?: (response: NotificationsApiResponse, eventType: 'NOTIFICATIONS'| 'UNVIEWED_COUNT') => {
# callback function to receive data
};
onStatusChange?: (status: 'SUCCESS' | 'FAILED' | 'PENDING') =>{
# callback function triggered when token verification status changes
}
}
```

Expand Down Expand Up @@ -93,23 +90,15 @@ Siren constructor accepts the following arguments

## Siren Methods

### 1. verifyToken

This method verifies the validity of the given tokens (recipientId and userToken).This method is called automatically while creating the instance . Once the verification is successful, the remaining exposed methods can be accessed.

```bash
await sirenInstance.verifyToken();
```

### 2. fetchUnviewedNotificationsCount
### 1. fetchUnviewedNotificationsCount

This method retrieves the count of unviewed notifications.

```bash
const { unviewedCount } = await sirenInstance.fetchUnviewedNotificationsCount()
```

### 3. fetchAllNotifications
### 2. fetchAllNotifications

This method retrieves list of notifications in a paginated manner.

Expand Down Expand Up @@ -192,7 +181,7 @@ Below are the accepted optional filters
}[]
```

### 4. startRealTimeFetch
### 3. startRealTimeFetch

By specifying the parameter eventType as either `NOTIFICATIONS` or `UNVIEWED_COUNT`, this method triggers the real-time retrieval of notifications or the count of unviewed notifications. If `NOTIFICATIONS` is selected, further parameters (`params`) can be provided for additional customization or filtering

Expand Down Expand Up @@ -253,7 +242,7 @@ Below are the accepted optional filters for `NOTIFICATIONS` event type
</tbody>
</table>

### 5. stopRealTimeFetch
### 4. stopRealTimeFetch

By specifying the parameter eventType as either `NOTIFICATIONS` or `UNVIEWED_COUNT`, this method stops the real-time retrieval of notifications or the count of unviewed notifications.

Expand All @@ -264,15 +253,15 @@ sirenInstance.stopRealTimeFetch(NOTIFICATIONS);
sirenInstance.stopRealTimeFetch(UNVIEWED_COUNT);
```

### 6. markAsReadById
### 5. markAsReadById

This method marks the notification as read. It accepts a notification id as an argument.

```bash
await sirenInstance.markAsReadById("your-notification-id");
```

### 7. markAsReadByDate
### 6. markAsReadByDate

This method marks the notifications as read till the given date.<br />
It accepts a param object as an argument with keys startDate (ISO date string) and category(string).
Expand All @@ -281,15 +270,15 @@ It accepts a param object as an argument with keys startDate (ISO date string) a
await sirenInstance.markAsReadByDate({startDate: "2011-10-05T14:48:00.000Z"});
```

### 8. deleteById
### 7. deleteById

This method deletes a notification. It accepts a notification id as an argument.

```bash
await sirenInstance.deleteById("your-notification-id");
```

### 9. deleteByDate
### 8. deleteByDate

This method deletes the notifications till the given date.<br />
It accepts a param object as an argument with keys startDate (ISO date string), isRead(boolean) and category(string).
Expand All @@ -298,7 +287,7 @@ It accepts a param object as an argument with keys startDate (ISO date string),
await sirenInstance.deleteByDate({startDate: "2011-10-05T14:48:00.000Z"});
```

### 10. markAllAsViewed
### 9. markAllAsViewed

This method marks the notifications as viewed till the given date. This sets the unviewed count as 0 <br />
It accepts an ISO date string as an argument
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sirenapp/js-sdk",
"version": "1.2.2",
"version": "1.2.3-rc.0",
"description": "JavaScript middleware designed to streamline interaction for managing and displaying in-app notifications seamlessly",
"main": "dist/umd/siren-js-umd-sdk.js",
"module": "dist/esm/siren-js-esm-sdk.js",
Expand Down
92 changes: 0 additions & 92 deletions src/Siren.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import SirenError from './error';
import {
verifyToken,
fetchUnviewedNotificationsCount,
fetchAllNotifications,
markAsReadById,
Expand All @@ -10,22 +9,18 @@ import {
} from './api';
import {
BulkUpdateType,
VerificationStatus,
ErrorMap,
SirenErrorTypes,
DATA_FETCH_INTERVAL,
ErrorLevelType,
EventType
} from './constants/generic';
import { getStartDate, sanitizeSession, emitSirenError } from './utils';

import type {
ErrorCallbackType,
FetchNotificationsParamsType,
InitConfigType,
ActionCallbackType,
NotificationsApiResponse,
VerifyTokenResponse,
NotificationDataType,
SirenErrorType,
NotificationDataResponse,
Expand All @@ -39,19 +34,16 @@ import type {
export class Siren {
private token: string;
private recipientId: string;
private onError: ErrorCallbackType;
private notificationFetchIntervalId: number | undefined;
private unViewedCountFetchIntervalId: number | undefined;
private latestNotification: NotificationDataType | null = null;
private actionCallbacks: ActionCallbackType | undefined;
private tokenValidationStatus: VerificationStatus = VerificationStatus.PENDING;
/**
* Binds specific class methods to ensure the correct `this` context when called.
* This is necessary for methods that are used asynchronously or passed as callbacks.
* @private
*/
private bindMethods() {
this.verifyToken = this.verifyToken.bind(this);
this.fetchUnviewedNotificationsCount = this.fetchUnviewedNotificationsCount.bind(this);
this.fetchAllNotifications = this.fetchAllNotifications.bind(this);
this.startRealTimeFetch = this.startRealTimeFetch.bind(this);
Expand Down Expand Up @@ -81,35 +73,11 @@ export class Siren {

this.token = session.data?.token || '';
this.recipientId = session.data?.recipientId || '';
this.onError = session.data?.onError;
this.actionCallbacks = actionCallbacks;

if (session.data) this.verifyToken();
this.bindMethods();
}

/**
* Verifies the validity of the user's recipient and token.
*
* @returns {Promise<VerifyTokenResponse | null>}
* - `VerifyTokenResponse` object containing status as SUCCESS.
* - `null` if the API fails to return a valid response.
*/
async verifyToken(): Promise<VerifyTokenResponse | null> {
this.tokenValidationStatus = VerificationStatus.PENDING;
const res = await verifyToken(this.token, this.recipientId, this.onError);

if (res)
this.tokenValidationStatus =
res && res.data?.status === VerificationStatus.SUCCESS
? VerificationStatus.SUCCESS
: VerificationStatus.FAILED; // api returns null in failed scenarios
if(this.actionCallbacks?.onStatusChange)
this.actionCallbacks.onStatusChange(this.tokenValidationStatus);

return res;
}

/**
* Retrieves the number of unviewed notifications count for the user.
*
Expand All @@ -118,9 +86,6 @@ export class Siren {
*
*/
async fetchUnviewedNotificationsCount(): Promise<UnviewedCountReturnResponse | null> {
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();

const response = await fetchUnviewedNotificationsCount(this.token, this.recipientId);

Expand All @@ -146,9 +111,6 @@ export class Siren {
async fetchAllNotifications(
params: FetchNotificationsParamsType
): Promise<NotificationsApiResponse | null> {
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
const response = await fetchAllNotifications(this.token, this.recipientId, params);

if (response && response?.data?.length && response?.data?.length > 0)
Expand All @@ -170,7 +132,6 @@ export class Siren {
eventType: EventType;
params?: FetchNotificationsParamsType;
}): void {
this.authorizeUserAction();
switch (eventType) {
case EventType.NOTIFICATION:
this.startRealTimeNotificationFetch(params ?? {});
Expand Down Expand Up @@ -208,9 +169,7 @@ export class Siren {
*/

async markAsReadById(id: string): Promise<NotificationDataResponse | null> {
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
let response;

if (id) response = await markAsReadById(this.token, this.recipientId, id);
Expand All @@ -230,9 +189,6 @@ export class Siren {

async markAsReadByDate(params: BulkUpdateParamsType): Promise<ActionResponse | null> {
const { startDate, category } = params || {};
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
let response;

if (startDate) {
Expand Down Expand Up @@ -265,9 +221,6 @@ export class Siren {
*/

async deleteById(id: string): Promise<ActionResponse | null> {
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
let response;

if (id) response = await deleteNotificationById(this.token, this.recipientId, id);
Expand All @@ -286,9 +239,7 @@ export class Siren {
*/
async deleteByDate(params: BulkUpdateParamsType): Promise<ActionResponse | null> {
const { startDate, isRead, category } = params || {};
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
let response;

if (startDate) {
Expand Down Expand Up @@ -322,9 +273,6 @@ export class Siren {
*
*/
async markAllAsViewed(startDate: string): Promise<MarkAsViewedResponse | null> {
const hasPermission = this.authorizeUserAction();

if (!hasPermission) return this.getErrorForUnauthorizedAction();
let response;

if (startDate)
Expand All @@ -349,7 +297,6 @@ export class Siren {
params.start ?? this.latestNotification?.createdAt ?? new Date().toISOString();

this.notificationFetchIntervalId = window.setInterval(async () => {
if (this.tokenValidationStatus !== VerificationStatus.SUCCESS) return null;
const response = await fetchAllNotifications(this.token, this.recipientId, {
...params,
...(lastFetchedCreatedAt && {
Expand Down Expand Up @@ -380,7 +327,6 @@ export class Siren {
*/
private startRealTimeUnviewedCountFetch(): void {
this.unViewedCountFetchIntervalId = window.setInterval(async () => {
if (this.tokenValidationStatus !== VerificationStatus.SUCCESS) return;
const response = await fetchUnviewedNotificationsCount(this.token, this.recipientId);

if (this.actionCallbacks?.onEventReceive)
Expand All @@ -404,44 +350,6 @@ export class Siren {

return { data: null, error };
}

private authorizeUserAction(): boolean {
if (this?.tokenValidationStatus === VerificationStatus.FAILED) {
const errorObj = new SirenError(
SirenErrorTypes.ERROR,
ErrorMap.UNAUTHORIZED_OPERATION.message,
ErrorMap.UNAUTHORIZED_OPERATION.code
);

if (this.onError) this.onError(errorObj.getError());

return false;
}
if (this?.tokenValidationStatus === VerificationStatus.PENDING) return false;

return true;
}

private getErrorForUnauthorizedAction() {
if (this?.tokenValidationStatus === VerificationStatus.PENDING)
return {
data: null,
error: {
Type: ErrorLevelType.ERROR,
Message: ErrorMap.AUTHENTICATION_PENDING.message,
Code: ErrorMap.AUTHENTICATION_PENDING.code
}
};

return {
data: null,
error: {
Type: ErrorLevelType.ERROR,
Message: ErrorMap.UNAUTHORIZED_OPERATION.message,
Code: ErrorMap.UNAUTHORIZED_OPERATION.code
}
};
}
}

if (window) window.Siren = Siren;
2 changes: 0 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import "promise-polyfill/src/polyfill";
import type {
VerificationStatus,
EventType,
ApiOperationType,
BulkUpdateType
Expand Down Expand Up @@ -158,7 +157,6 @@ export type ActionCallbackType = {
response: NotificationsApiResponse | UnviewedCountApiResponse,
eventType: EventType
) => void;
onStatusChange?: (status: VerificationStatus) => void;
};

/**
Expand Down
3 changes: 1 addition & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ export function sanitizeSession(
code: ErrorMap.INVALID_CREDENTIALS.code
};
} else if (
(actionCallbacks?.onEventReceive && typeof actionCallbacks.onEventReceive !== 'function') ||
(actionCallbacks?.onStatusChange && typeof actionCallbacks.onStatusChange !== 'function')
(actionCallbacks?.onEventReceive && typeof actionCallbacks.onEventReceive !== 'function')
) {
emitSirenError(
SirenErrorTypes.CONFIG_ERROR,
Expand Down
Loading