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

loopback4-notifications

v8.0.3

Published

An extension for setting up various notification mechanisms in loopback4 application, vis-a-vis, Push notification, SMS notification, Email notification.

Downloads

3,242

Readme

loopback4-notifications

Overview

This is a loopback-next extension for adding different notification mechanisms vis-à-vis, Push, SMS, Email to any loopback 4 based REST API application or microservice.

It provides a generic provider-based framework to add your own implementation or implement any external service provider to achieve the same. There are 3 different providers available to be injected namely, PushProvider, SMSProvider and EmailProvider. It also provides support for 7 very popular external services for sending notifications.

  1. AWS Simple Email Service - It's one of the EmailProvider for sending email messages.
  2. AWS Simple Notification Service - It's one of the SMSProvider for sending SMS notifications.
  3. Pubnub - It's one of the PushProvider for sending realtime push notifications to mobile applications as well as web applications.
  4. Socket.IO - It's one of the PushProvider for sending realtime push notifications to mobile applications as well as web applications.
  5. FCM - It's one of the PushProvider for sending realtime push notifications to mobile applications as well as web applications.
  6. Nodemailer - It's one of the EmailProvider for sending email messages.
  7. Apple Push Notification service - It's one of the push notification providers that integrates notification service created by Apple Inc. that enables third party application developers to send notification data to applications installed on Apple devices.
  8. Twilio SMS Service - Twilio is a modern communication API Used by developers for establishing communications. Twilio can be used for sending SMS or Whatapp notifications. You can use one of these services or add your own implementation or integration using the same interfaces and attach it as a provider for that specific type.

You can use one of these services or add your own implementation or integration using the same interfaces and attach it as a provider for that specific type.

Installation

npm install loopback4-notifications

Usage

In order to use this component into your LoopBack application, please follow below steps.

Add component to application.

// application.ts
import {NotificationsComponent} from 'loopback4-notifications';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    // ...
  }
}

After the above, you need to configure one of the notification provider at least. Based upon the requirement, please choose and configure the respective provider for sending notifications. See below.

Email Notifications using Amazon Simple Email Service

This extension provides in-built support of AWS Simple Email Service integration for sending emails from the application. In order to use it, run npm install aws-sdk, and then bind the SesProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SesProvider} from 'loopback4-notifications/ses';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.EmailProvider).toProvider(SesProvider);
    // ...
  }
}

There are some additional configurations needed in order to allow SES to connect to AWS. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SesProvider, SESBindings} from 'loopback4-notifications/ses';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(SESBindings.Config).to({
      accessKeyId: process.env.SES_ACCESS_KEY_ID,
      secretAccessKey: process.env.SES_SECRET_ACCESS_KEY,
      region: process.env.SES_REGION,
    });
    this.bind(NotificationBindings.EmailProvider).toProvider(SesProvider);
    // ...
  }
}

All the configurations as specified by AWS docs here are supported in above SESBindings.Config key.

In addition to this, some general configurations can also be done, like below.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SesProvider, SESBindings} from 'loopback4-notifications/ses';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.Config).to({
      sendToMultipleReceivers: false,
      senderEmail: '[email protected]',
    });
    this.bind(SESBindings.Config).to({
      accessKeyId: process.env.SES_ACCESS_KEY_ID,
      secretAccessKey: process.env.SES_SECRET_ACCESS_KEY,
      region: process.env.SES_REGION,
    });
    this.bind(NotificationBindings.EmailProvider).toProvider(SesProvider);
    // ...
  }
}

Possible configuration options for the above are mentioned below.

| Option | Type | Description | | ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | sendToMultipleReceivers | boolean | If set to true, single email will be sent to all receivers mentioned in payload. If set to false, multiple emails will be sent for each receiver mentioned in payload. | | senderEmail | string | This will be used as from email header in sent email. |

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to SesProvider we have. Add that provider in place of SesProvider. Refer to the implementation here.

this.bind(NotificationBindings.EmailProvider).toProvider(MyOwnProvider);

Email Notifications Using Nodemailer

This extension provides in-built support of Nodemailer integration for sending emails from the application. In order to use it, run npm install nodemailer, and then bind the NodemailerProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {NodemailerProvider} from 'loopback4-notifications/nodemailer';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.EmailProvider).toProvider(
      NodemailerProvider,
    );
    // ...
  }
}

There are some additional configurations needed in order to allow NodeMailer to works. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {
  NodemailerProvider,
  NodemailerBindings,
} from 'loopback4-notifications/nodemailer';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NodemailerBindings.Config).to({
      pool: true,
      maxConnections: 100,
      url: '',
      host: 'smtp.example.com',
      port: 80,
      secure: false,
      auth: {
        user: 'username',
        pass: 'password',
      },
      tls: {
        rejectUnauthorized: true,
      },
    });
    this.bind(NotificationBindings.EmailProvider).toProvider(
      NodemailerProvider,
    );
    // ...
  }
}

All the configurations as specified by Nodemailer docs for SMTP transport here are supported in above NodemailerBindings.Config key.

In addition to this, some general configurations can also be done, like below.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {
  NodemailerProvider,
  NodemailerBindings,
} from 'loopback4-notifications/nodemailer';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.Config).to({
      sendToMultipleReceivers: false,
      senderEmail: '[email protected]',
    });
    this.bind(NodemailerBindings.Config).to({
      pool: true,
      maxConnections: 100,
      url: '',
      host: 'smtp.example.com',
      port: 80,
      secure: false,
      auth: {
        user: 'username',
        pass: 'password',
      },
      tls: {
        rejectUnauthorized: true,
      },
    });
    this.bind(NotificationBindings.EmailProvider).toProvider(
      NodemailerProvider,
    );
    // ...
  }
}

Possible configuration options for the above are mentioned below.

| Option | Type | Description | | ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | sendToMultipleReceivers | boolean | If set to true, single email will be sent to all receivers mentioned in payload. If set to false, multiple emails will be sent for each receiver mentioned in payload. | | senderEmail | string | This will be used as from email header in sent email. |

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to NodemailerProvider we have. Add that provider in place of NodemailerProvider. Refer to the implementation here.

this.bind(NotificationBindings.EmailProvider).toProvider(MyOwnProvider);

SMS Notifications using AWS SNS

This extension provides in-built support of AWS Simple Notification Service integration for sending SMS from the application. In order to use it, run npm install aws-sdk, and then bind the SnsProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SnsProvider} from 'loopback4-notification/sns';
// ...

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.SMSProvider).toProvider(SnsProvider);
    // ...
  }
}

There are some additional configurations needed in order to allow SNS to connect to AWS. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SNSBindings, SnsProvider} from 'loopback4-notification/sns';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(SNSBindings.Config).to({
      accessKeyId: process.env.SNS_ACCESS_KEY_ID,
      secretAccessKey: process.env.SNS_SECRET_ACCESS_KEY,
      region: process.env.SNS_REGION,
    });
    this.bind(NotificationBindings.SMSProvider).toProvider(SnsProvider);
    // ...
  }
}

All the configurations as specified by AWS docs here are supported in above SNSBindings.Config key.

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to SnsProvider we have. Add that provider in place of SnsProvider.Refer to the implementation here.

this.bind(NotificationBindings.SMSProvider).toProvider(MyOwnProvider);

SMS / Whatsapp Notifications using Twilio

This extension provides in-built support of Twilio integration for sending SMS / whatsapp notifications from the application. In order to use it, run npm install twilio, and then bind the TwilioProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {
  TwilioProvider
} from 'loopback4-notification/twilio';
....

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    ....

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.SMSProvider).toProvider(TwilioProvider);
    ....
  }
}

There are some additional configurations needed in order to connect to Twilio. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {
  TwilioBindings,
  TwilioProvider
} from 'loopback4-notification/twilio';
....

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    ....

    this.component(NotificationsComponent);
    this.bind(TwilioBindings.Config).to({
      accountSid: process.env.TWILIO_ACCOUNT_SID,
      authToken: process.env.TWILIO_AUTH_TOKEN,
      waFrom: process.env.TWILIO_WA_FROM,
      smsFrom: process.env.TWILIO_SMS_FROM,
      waStatusCallback:process.env.TWILIO_WA_STATUS_CALLBACK,
      smsStatusCallback:process.env.TWILIO_SMS_STATUS_CALLBACK,
    });
    this.bind(NotificationBindings.SMSProvider).toProvider(TwilioProvider);
    ....
  }
}

All the configurations as specified by Twilio docs and console are supported in above TwilioBindings Config key. smsFrom could be messaging service id, twilio number or short code. waFrom could be whats app number or number associated to channel.

Push Notifications with Pubnub

This extension provides in-built support of Pubnub integration for sending realtime push notifications from the application. In order to use it, run npm install pubnub, and then bind the PushProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {PubNubProvider} from 'loopback4-notifications/pubnub';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.PushProvider).toProvider(PubNubProvider);
    // ...
  }
}

There are some additional configurations needed in order to allow Pubnub connection. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {PubnubBindings, PubNubProvider} from 'loopback4-notifications/pubnub';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(PubNubProvider.Config).to({
      subscribeKey: process.env.PUBNUB_SUBSCRIBE_KEY,
      publishKey: process.env.PUBNUB_PUBLISH_KEY,
      secretKey: process.env.PUBNUB_SECRET_KEY,
      ssl: true,
      logVerbosity: true,
      uuid: 'my-app',
      cipherKey: process.env.PUBNUB_CIPHER_KEY,
      apns2Env: 'production',
      apns2BundleId: 'com.app.myapp',
    });
    this.bind(NotificationBindings.PushProvider).toProvider(PubNubProvider);
    // ...
  }
}

All the configurations as specified by Pubnub docs here are supported in above PubNubProvider.Config key.

Additionally, PubNubProvider also supports Pubnub Access Manager integration. Refer docs here for details.

For PAM support, PubNubProvider exposes two more methods - grantAccess and revokeAccess. These can be used to grant auth tokens and revoke them from Pubnub.

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to PubNubProvider we have. Add that provider in place of PubNubProvider. Refer to the implementation here.

this.bind(NotificationBindings.PushProvider).toProvider(MyOwnProvider);

Push Notifications With Socket.io

This extension provides in-built support of Socket.io integration for sending realtime notifications from the application. In order to use it, run npm install socket.io-client, and bind the PushProvider as below in application.ts.

This provider sends the message to the channel passed via config (or while publishing) and accepts a fix interface to interact with. The interface could be imported into the project by the name SocketMessage.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {SocketIOProvider} from 'loopback4-notifications/socketio';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(NotificationBindings.PushProvider).toProvider(SocketIOProvider);
    // ...
  }
}

There are some additional configurations needed in order to allow Socket connection. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {
  SocketBindings,
  SocketIOProvider,
} from 'loopback4-notifications/socketio';

export class NotificationServiceApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...

    this.component(NotificationsComponent);
    this.bind(SocketBindings.Config).to({
      url: process.env.SOCKETIO_SERVER_URL,
    });
    this.bind(NotificationBindings.PushProvider).toProvider(SocketIOProvider);
    // ...
  }
}

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to SocketIOProvider we have. Add that provider in place of SocketIOProvider. Refer to the implementation here.

this.bind(NotificationBindings.PushProvider).toProvider(MyOwnProvider);

Push Notifications With FCM

This extension provides in-built support of Firebase Cloud Messaging integration for sending realtime push notifications from the application. In order to use it, run npm i firebase-admin, and then bind the PushProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {FcmProvider} from 'loopback4-notifications/fcm';
export class MyApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...
    this.component(NotificationsComponent);
    this.bind(NotificationBindings.PushProvider).toProvider(FcmProvider);
    // ...
  }
}

There are some additional configurations needed in order to use Firebase Cloud Messaging. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {FcmProvider, FcmBindings} from 'loopback4-notifications/fcm';
export class MyApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...
    this.component(NotificationsComponent);
    this.bind(FcmBindings.Config).to({
      apiKey: 'API_KEY',
      authDomain: 'PROJECT_ID.firebaseapp.com',
      // The value of `databaseURL` depends on the location of the database
      databaseURL: 'https://DATABASE_NAME.firebaseio.com',
      projectId: 'PROJECT_ID',
      storageBucket: 'PROJECT_ID.appspot.com',
      messagingSenderId: 'SENDER_ID',
      appId: 'APP_ID',
      // For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
      measurementId: 'G-MEASUREMENT_ID',
    });
    this.bind(NotificationBindings.PushProvider).toProvider(FcmProvider);
    // ...
  }
}

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to FcmProvider we have. Add that provider in place of FcmProvider. Refer to the implementation here.

this.bind(NotificationBindings.PushProvider).toProvider(MyOwnProvider);

Push Notifications With APNs

This extension provides in-built support of Apple Push Notification service for sending notification to applications installed on Apple devices. In order to use it bind the PushProvider as below in application.ts.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {ApnsProvider} from 'loopback4-notifications/apns';
export class MyApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...
    this.component(NotificationsComponent);
    this.bind(NotificationBindings.PushProvider).toProvider(ApnsProvider);
    // ...
  }
}

There are some additional configurations needed in order to use Apple Push Notification service. You need to add them as below. Make sure these are added before the provider binding.

import {
  NotificationsComponent,
  NotificationBindings,
} from 'loopback4-notifications';
import {ApnsProvider, ApnsBinding} from 'loopback4-notifications/apns';
export class MyApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // ...
    this.component(NotificationsComponent);
    this.bind(ApnsBinding.Config).to({
      providerOptions: {
        /* APNs Connection options, see below. */
      };
      options: {
        badge: 1, // optional
        topic: "string"
      };
    });
    this.bind(NotificationBindings.PushProvider).toProvider(ApnsProvider);
    // ...
  }
}

For more information about providerOptions check: provider documentation

If you wish to use any other service provider of your choice, you can create a provider for the same, similar to ApnsProvider we have. Add that provider in place of ApnsProvider. Refer to the implementation here.

this.bind(NotificationBindings.PushProvider).toProvider(MyOwnProvider);

Controller Usage

Once the providers are set, the implementation of notification is very easy. Just add an entity implementing the Message interface provided by the component. For specific type, you can also implement specific interfaces like, SMSMessage, PushMessage, EmailMessage. See example below.

import {Entity, model, property} from '@loopback/repository';
import {
  Message,
  Receiver,
  MessageType,
  MessageOptions,
} from 'loopback4-notifications';

@model({
  name: 'notifications',
})
export class Notification extends Entity implements Message {
  @property({
    type: 'string',
    id: true,
  })
  id?: string;

  @property({
    type: 'string',
    jsonSchema: {
      nullable: true,
    },
  })
  subject?: string;

  @property({
    type: 'string',
    required: true,
  })
  body: string;

  @property({
    type: 'object',
    required: true,
  })
  receiver: Receiver;

  @property({
    type: 'number',
    required: true,
  })
  type: MessageType;

  @property({
    type: 'date',
    name: 'sent',
  })
  sentDate: Date;

  @property({
    type: 'object',
  })
  options?: MessageOptions;

  constructor(data?: Partial<Notification>) {
    super(data);
  }
}

After this, you can publish notification from controller API methods as below. You don't need to invoke different methods for different notification. Same publish method will take care of it based on message type sent in request body.

export class NotificationController {
  constructor(
    // ...
    @inject(NotificationBindings.NotificationProvider)
    private readonly notifProvider: INotification,
  ) {}

  @post('/notifications', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Notification model instance',
        content: {
          [CONTENT_TYPE.JSON]: {schema: getModelSchemaRef(Notification)},
        },
      },
    },
  })
  async create(
    @requestBody({
      content: {
        [CONTENT_TYPE.JSON]: {
          schema: getModelSchemaRef(Notification, {exclude: ['id']}),
        },
      },
    })
    notification: Omit<Notification, 'id'>,
  ): Promise<Notification> {
    await this.notifProvider.publish(notification);
  }
}

As you can see above, one controller method can now cater to all the different type of notifications.

Feedback

If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can. If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.

Contributing

Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Code of conduct

Code of conduct guidelines here.

License

MIT