npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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;

  1. WebPushNotificationModel:
    This model allows you to define Web Push notification parameters. You can customize values such as icon, badge, vibrate, etc.
    Example Usage:
    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' });
    Properties:
    icon: Icon URL. Default value is null.
    badge: Badge icon URL. Default value is null.
    tag: Notification tag to uniquely identify notifications. Default value is null.
    requireInteraction: Boolean to require user interaction for the notification. Default value is false.
    renotify: Enable renotify or not. Default value is false.
    silent: Boolean to set the notification to silent. Default value is true.
    timestamp: The timestamp of the notification. Default value is Date.now().
    lang: Language code (e.g., 'en' for English). Default value is ru.
    vibrate: Vibrate pattern (e.g., [100, 50, 100]). Default value is [200, 100, 200].
  2. 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:
     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);
    Properties:
    icon: Icon URL. Default value is null.
    color: Notification icon color in #rrggbb format. Default value is #000000.
    sound: Sound to play when notification arrives. Default value is default.
    tag: Notification tag. Default value is null.
    imageUrl: URL of an image to be displayed in the notification. Default value is null.
    clickAction: Action associated with a user click. Default value is null.
    bodyLocKey: Key for the body text localization. Default value is null.
    titleLocKey: Key for the title text localization. Default value is null.
    channelId: Android notification channel ID. Default value is null.
    vibrateTimingsMillis: Array defining the vibrate pattern. Default value is [0, 500, 1000].
    sticky: Boolean indicating if the notification is sticky (persistent). Default value is false.
    eventTimestamp: Timestamp when the event in the notification occurred. Default value is new Date().
    notificationCount: Count to represent number of items in the notification. Default value is 0.
  3. IosNotificationModel:
    This model allows you to define iOS Push notification parameters. You can customize values like alert messages, sound, badge, and more.
    Example Usage:
     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');
    Properties:
    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 is 0.
    sound: Sound to play with the notification. Default value is default.
    contentAvailable: Boolean indicating if the notification configures a background update. Default value is false.
    mutableContent: Boolean indicating if the notification is mutable. Default value is false.
    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 {}.