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

@bgroup/notifications

v1.0.0

Published

Notifications manager

Downloads

1

Readme

Notifier - Firebase Web and Mobile Notifications

Notifier is a package designed to handle web and mobile notifications through Firebase, providing a seamless integration for messaging across different devices.

Features

  • Easy integration with Firebase for push notifications.
  • Automatic device detection for appropriate instance handling.
  • Reactive model integration for state management.
  • Callbacks for message receipt and error handling.

Installation

npm install notifier --save

Listen for notifications

To use Notifier, you need to import it, instantiate it, set up your message received and error handlers, and initialize it with your Firebase credentials.

Here is a quick start example:

import { Notifier } from '@bgroup/notifications/entities.ts';

// Define your Firebase credentials
const credentials = {
	VAPID_KEY: 'your_vapid_key',
	apiKey: 'your_api_key',
	authDomain: 'your_auth_domain',
	projectId: 'your_project_id',
	storageBucket: 'your_storage_bucket',
	messagingSenderId: 'your_messaging_sender_id',
	appId: 'your_app_id',
};

// Create an instance of Notifier
const notifier = new Notifier();

// Set the message received handler
notifier.onMessageReceived = message => {
	console.log('Message received => ', message);
};

// Set the message error handler
notifier.onMessageError = error => {
	console.error('Message error => ', error);
};

// Initialize Notifier with your Firebase credentials
await notifier.init({ credentials });

Replace the placeholder credentials with your actual Firebase configuration.

API Reference

Below are the main components that you can use with Notifier:

Notifier

The main class that you'll interact with.

new Notifier()

Creates a new Notifier instance.

onMessageReceived

Callback function that gets called when a new message is received.

deviceToken

Device token generated by firebase (string)

onMessageError

Callback function that gets called when there is an error in message reception.

init(options)

Initializes the notification service with the provided Firebase credentials.

  • options: Object containing the credentials and other options.
    • credentials: Your Firebase project credentials.

Device Detection

Notifier automatically detects the device type (mobile or web) and instantiates the appropriate object for handling notifications specific to that platform.

Sending Notifications

This guide provides instructions on how to set up and send notifications using Firebase Cloud Messaging (FCM) within our system.

Firebase Server Credentials Setup

To send notifications, you must first set up your Firebase server credentials. These can be obtained from your Firebase project's console.

// Replace the following placeholders with your actual Firebase credentials.
const firebaseServerCredentials = {
	type: 'type',
	project_id: 'project_id',
	private_key_id: 'private_key_id',
	private_key: 'private_key',
	client_email: 'client_email',
	client_id: 'client_id',
	auth_uri: 'auth_uri',
	token_uri: 'token_uri',
	auth_provider_x509_cert_url: 'auth_provider_x509_cert_url',
	client_x509_cert_url: 'client_x509_cert_url',
	universe_domain: 'universe_domain',
};

// IMPORTANT: Do not hardcode your real credentials in your source code.
// Store them in a secure location and load them into your environment securely.

To send a notification, you need to instantiate NotifierBridge and construct the notification object with a title, body, and device token.

import { NotifierBridge } from '@bgroup/notifications/models.bridge';

// Instantiating the notification bridge
const notifierBridge = new NotifierBridge();

// Constructing the notification payload
const notification = {
	notification: {
		title: 'This is a notification test',
		body: 'This is a notification body',
	},
	token: 'DEVICE_TOKEN', // Replace with the device token obtained from your notifier instance
};

// Sending the notification
await notifierBridge.send(firebaseServerCredentials, notification);

Obtaining the Device Token

The device token needed to send the notification can be retrieved from your Notifier instance, as mentioned in the first use case.

const deviceToken = notifier.deviceToken;

Security and Best Practices

  • Credential Storage: As previously mentioned, it's critical to securely store credentials using environment variables or managed secrets services.
  • Error Handling: Implement proper error handling to capture and respond to any issues encountered when sending notifications.

Conclusion

The above setup will allow you to send notifications through Firebase. Make sure to follow the security best practices and never expose sensitive credentials within your codebase.

For more details on implementing notification features or handling device tokens, please refer to the official Firebase documentation or reach out for further assistance.

MultiDevice notifications

Subscribing and unsubscribing to topics in Firebase Cloud Messaging (FCM) is a way to send notifications to groups of users who are interested in certain subjects, rather than individual device tokens. This allows for more efficient message delivery when broadcasting to a large audience.

Here's how your use case can be structured:

SuscribeToTopic Function

import { Subscriptions } from 'path-to-subscriptions-module';

class NotifierBridge {
	/**
	 * Subscribes a list of tokens to a specified topic.
	 * @param tokens - An array of tokens to be subscribed.
	 * @param topic - The topic to which tokens should be subscribed.
	 * @returns The result of the subscribe function.
	 */
	async suscribeToTopic(tokens: string[], topic: string): Promise<any> {
		// Logic to subscribe tokens to a topic, potentially using Firebase Admin SDK
		return Subscriptions.subscribe(tokens, topic);
	}

	// ... other class methods
}

UnsubscribeToTopic Function

import { Subscriptions } from 'path-to-subscriptions-module';

class NotifierBridge {
	/**
	 * Unsubscribes a list of tokens from a specified topic.
	 * @param tokens - An array of tokens to be unsubscribed.
	 * @param topic - The topic from which tokens should be unsubscribed.
	 * @returns The result of the unsubscribe function.
	 */
	async unsubscribeFromTopic(tokens: string[], topic: string): Promise<any> {
		// Logic to unsubscribe tokens from a topic, potentially using Firebase Admin SDK
		return Subscriptions.unsubscribe(tokens, topic);
	}

	// ... other class methods
}

Sending Notifications to a Topic

import { NotifierBridge } from 'path-to-notifier-bridge';

const notifierBridge = new NotifierBridge();

// Subscribing devices to a topic
await notifierBridge.suscribeToTopic(['deviceToken1', 'deviceToken2'], 'lavanderia');

// Constructing a multi-device notification payload
const multiDeviceNotification = {
	notification: {
		title: 'Multi device notification test',
		body: 'This is the body for the multi device notification test',
	},
	topic: 'lavanderia', // The topic to which the notification should be sent
};

// Sending the notification to a topic
await notifierBridge.send(firebaseServerCredentials, multiDeviceNotification);

Best Practices

  1. Asynchronous Handling: Ensure that the subscribe and unsubscribe functions are properly awaited or handled asynchronously since these are network requests that will take time to complete.

  2. Error Handling: Implement try-catch blocks or equivalent error handling around network requests to handle any potential failures.

  3. Validation: Validate the tokens array and topic string before attempting to subscribe or unsubscribe to prevent invalid requests.

  4. Feedback Handling: Handle feedback from FCM regarding invalid tokens or subscription status to maintain a clean and efficient messaging system.

  5. Security: When dealing with tokens and sensitive operations like subscribing and unsubscribing, make sure the requests are authenticated and authorized if these operations are exposed through an API.

  6. Testing: Ensure to test these functionalities in a controlled environment before deploying them to production to avoid mass subscription/unsubscription errors.

Incorporating these functionalities will enable you to manage topic subscriptions effectively. Make sure to refer to the Firebase documentation for any specific details regarding their SDK and API limitations or best practices.

Nota 📌

To correctly implement the library, it is necessary to provide the firebase-messaging-sw.js file located at the root of the package. The only change needed would be to use your application's Firebase credentials. If you are implementing this package with Beyond, you need to specify the file's name in your project's package.json using the static entry, for example:

Texto alternativo

Consequently, the file should be placed in the root of the package.

Contributing

Please feel free to contribute to the development of Notifier. You can clone the repository, create a new branch for your features or fixes, and submit a pull request.

License

Your package is licensed under the MIT License - see the LICENSE file for details.