gogym-libs
v0.0.4
Published
The `gogym-notifications` library allows you to easily send push notifications using Firebase Cloud Messaging (FCM) for iOS, Android, and Web platforms. It provides a simple and extensible way to manage different types of notifications with customizable
Downloads
350
Readme
gogym-notifications
Library
The gogym-notifications
library allows you to easily send push notifications using Firebase Cloud Messaging (FCM) for iOS, Android, and Web platforms.
It provides a simple and extensible way to manage different types of notifications with customizable payloads for each platform and includes an optional
feature to save notifications to a database via an external handler.
Installation
1. Install the Library
If you're working within a NestJS project, you can add the gogym-libs
library as a dependency:
npm install gogym-libs
2. Install Firebase SDK
The library requires Firebase SDK to interact with Firebase Cloud Messaging:
npm install firebase-admin
Usage
After installing the library, you can integrate it into your NestJS application.
1. Import the GogymNotificationsModule Module
In your NestJS project, import the GogymNotificationsModule into the module where you want to use notifications:
import { Module } from '@nestjs/common';
import { GogymNotificationsModule } from 'gogym-libs/dist/gogym-notifications';
import * as firebase from 'firebase-admin';
@Module({
imports: [
GogymNotificationsModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
// projectId: configService.get<string>('FIREBASE_PROJECT_ID'), // NOTE: You might need to specify it.
credential: firebase.credential.cert({
type: configService.get<string>('FIREBASE_TYPE'),
projectId: configService.get<string>('FIREBASE_PROJECT_ID'),
privateKeyId: configService.get<string>('FIREBASE_PROJECT_KEY_ID'),
private_key: configService.get<string>('FIREBASE_PRIVATE_KEY'),
client_email: configService.get<string>('FIREBASE_CLIENT_EMAIL'),
clientId: configService.get<string>('FIREBASE_CLIENT_ID'),
authUri: configService.get<string>('FIREBASE_AUTH_URI'),
tokenUri: configService.get<string>('FIREBASE_TOKEN_URI'),
authProviderX509CertUrl: configService.get<string>(
'FIREBASE_AUTH_PROVIDER_X_509_CERT_URL',
),
clientX509CertUrl: configService.get<string>(
'FIREBASE_CLIENT_C_509_CERT_URL',
),
universeDomain: configService.get<string>('FIREBASE_UNIVERSE_DOMAIN'),
databaseURL: configService.get<string>('FIREBASE_DATABASE_URL'),
} as firebase.ServiceAccount),
databaseURL: configService.get<string>('FIREBASE_DATABASE_URL'),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}
2. Send a Notification
To send a notification, you can use the GogymNotificationsService
with any of the notification models.
Example using WebPushNotificationModel
:
import { Injectable } from '@nestjs/common';
import { GogymNotificationsService, WebPushNotificationModel } from 'gogym-libs/dist/gogym-notifications';
@Injectable()
export class PushNotificationService {
constructor(private gogymNotificationsService: GogymNotificationsService) {}
async sendNotification(fcmToken: string) {
const webPushNotification = new WebPushNotificationModel(':rocket:')
.setIcon('icon-url')
.setTag('new-notification')
.setRequireInteraction(true)
.setSilent(false)
.setTimestamp(Date.now())
.setLang('en')
.setVibrate([100, 50, 100])
const message = webPushNotification.build();
await this.gogymNotificationsService.push(fcmToken, message);
}
}
3. Send and Save Notifications to the Database
With the new pushAndSaveToDatabase method, you can send notifications and optionally save them to a database, if they are marked for saving.
This feature requires setting up a saveHandler in the application, which will handle the saving logic.
Define a Save Handler
In your application, define a saveHandler function to save notifications. This function can perform any required database operations.
import { NotificationsRepository } from './notifications.repository';
import { Injectable } from '@nestjs/common';
import { GogymNotificationsService } from 'gogym-libs/dist/gogym-notifications';
@Injectable()
export class PushNotificationService {
constructor(
private readonly gogymNotificationsService: GogymNotificationsService,
private readonly notificationsRepository: NotificationsRepository,
) {
const saveHandler = async (notification) => {
await this.notificationsRepository.save(notification);
};
this.gogymNotificationsService.setSaveHandler(saveHandler);
}
}
Use pushAndSaveToDatabase in Your Controller
In the controller, you can now use pushAndSaveToDatabase
to send and save notifications.
This method will save notifications only if they are marked with markForSave()
.
import { Controller, Post, Body } from '@nestjs/common';
import { GogymNotificationsService, WebPushNotificationModel } from 'gogym-libs/dist/gogym-notifications';
@Controller('notifications')
export class NotificationsController {
constructor(
private readonly gogymNotificationsService: GogymNotificationsService,
) {}
@Post('send')
async sendNotification(@Body('token') fcmToken: string) {
const notification = new WebPushNotificationModel('New message')
.setTitle('Hello World')
.setSilent(false)
.markForSave(); // Marks this notification to be saved to the database
await this.gogymNotificationsService.pushAndSaveToDatabase(fcmToken, notification);
return { message: 'Notification sent and saved if marked.' };
}
}
Notification Models
The gogym-notifications
library provides various notification models, each with specific setters and parameters for iOS, Android, and Web push notifications.
Note: Each notification-related model extends the NotificationModel, which has the following properties:
senderId
: Specifies the sender of the notification.recipientId
: Specifies the recipient of the notification.recipientMetadata
: Specifies the recipient metadata.senderMetadata
: Specifies the sender metadata.title
: Specifies the notification title.body
: Specifies the notification body.priority
: Specifies the notification priority.data
: Specifies the notification data, which can be in any JSON format.
Let's take a look at the models;
- WebPushNotificationModel:
This model allows you to define Web Push notification parameters. You can customize values such as icon, badge, vibrate, etc.
Example Usage:
Properties:const webPushNotification = new WebpushNotificationModel(':rocket:') .setIcon('icon-url') .setTag('new-notification') .setRequireInteraction(true) .setRenotify(true) .setSilent(false) .setTimestamp(Date.now()) .setLang('en') .setVibrate([100, 50, 100]) .setCustomData({ customKey: 'customValue' });
icon
: Icon URL. Default value isnull
.badge
: Badge icon URL. Default value isnull
.tag
: Notification tag to uniquely identify notifications. Default value isnull
.requireInteraction
: Boolean to require user interaction for the notification. Default value isfalse
.renotify
: Enable renotify or not. Default value isfalse
.silent
: Boolean to set the notification to silent. Default value istrue
.timestamp
: The timestamp of the notification. Default value isDate.now()
.lang
: Language code (e.g., 'en' for English). Default value isru
.vibrate
: Vibrate pattern (e.g., [100, 50, 100]). Default value is[200, 100, 200]
. - AndroidNotificationModel:
This model allows you to define Android Push notification parameters. You can customize values such as sound, icon, click action, vibrate patterns, etc.
Example Usage:
Properties:const androidNotification = new AndroidNotificationModel('New Android Notification') .setIcon('icon-url') .setColor('#FF5733') .setSound('default') .setTag('new-notification') .setClickAction('OPEN_APP') .setBodyLocKey('message') .setTitleLocKey('notification_title') .setChannelId('notification_channel') .setVibrateTimingsMillis([0, 500, 1000]) .setSticky(true) .setEventTimestamp(new Date()) .setNotificationCount(5);
icon
: Icon URL. Default value isnull
.color
: Notification icon color in #rrggbb format. Default value is#000000
.sound
: Sound to play when notification arrives. Default value isdefault
.tag
: Notification tag. Default value isnull
.imageUrl
: URL of an image to be displayed in the notification. Default value isnull
.clickAction
: Action associated with a user click. Default value isnull
.bodyLocKey
: Key for the body text localization. Default value isnull
.titleLocKey
: Key for the title text localization. Default value isnull
.channelId
: Android notification channel ID. Default value isnull
.vibrateTimingsMillis
: Array defining the vibrate pattern. Default value is[0, 500, 1000]
.sticky
: Boolean indicating if the notification is sticky (persistent). Default value isfalse
.eventTimestamp
: Timestamp when the event in the notification occurred. Default value isnew Date()
.notificationCount
: Count to represent number of items in the notification. Default value is0
. - IosNotificationModel:
This model allows you to define iOS Push notification parameters. You can customize values like alert messages, sound, badge, and more.
Example Usage:
Properties:const iosNotification = new IosNotificationModel('New iOS Notification') .setAlert('You have a new message') .setBadge(5) .setSound('default') .setContentAvailable(true) .setMutableContent(true) .setCategory('message') .setThreadId('12345');
alert
: The alert message or an object for custom alert. Default value is''
.badge
: The badge number to be displayed on the app icon. Default value is0
.sound
: Sound to play with the notification. Default value isdefault
.contentAvailable
: Boolean indicating if the notification configures a background update. Default value isfalse
.mutableContent
: Boolean indicating if the notification is mutable. Default value isfalse
.category
: Category to associate with the notification. Default value is''
.threadId
: Thread ID for grouping notifications. Default value is''
.customData
: Custom data for the notification. Default value is an empty object{}
.