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

@globaluy/notifications

v1.0.3

Published

Notifications API

Downloads

202

Readme

Description

Notifications API is a notification module to handle email, push, sms and slack messages.

Installation

$ npm install @globaluy/notifications

MIGRATION GUIDE

Para los que usábamos la versión de submodulo revisar la guía de migración para actualizar a esta librería.

Post-installation

Notifications API uses TypeORM as ORM. It relies on 3 tables in order to work properly.

  • notifications
  • notification_logs
  • notification_black_list

It works out the box if synchronize is turned on. If it is off then there are a couple of options that you can use:

  • create the tables manually using the init.sql script.
  • generate the migrations pointing to the location of the entities of this package.
      entities: [
          '...',
          './node_modules/@globaluy/notifications/src/entities/**/*.entity{.ts,.js}',
        ],
  • run existing migrations in this package's migration folder.

How to use it.

Create notifications.config file in config folder of the root project:

//see configuration sample below.
export const notifications = () => ({
   return {
    enabled: env.SEND_EMAILS,
    whitelist: env.EMAILS_WHITE_LIST?.split(','),
    maxAttempts: 2,
    sendLimit: 100,
    account: {
      port: Number(env.EMAIL_SMTP_PORT),
      host: String(env.EMAIL_HOST),
      username: String(env.EMAIL_USER),
      password: String(env.EMAIL_PASSWORD),
      alias: env.EMAIL_FROM,
    },
    from: String(env.EMAIL_FROM),
    templates: String(env.EMAIL_TEMPLATES_PATH),
    push: {
      enabled: env.SEND_PUSH,
      credentialJson: env.FIREBASE_CREDENTIAL_JSON,
      parallelLimit: Number(env.FIREBASE_PARALLEL_LIMIT),
    },
    //configurada en Docker compose
    stopCron: Boolean(+process.env.STOP_CRON),
    slack: {
      enabled: env.SEND_SLACK,
      appToken: env.SLACK_APP_TOKEN,
    },
    twilio: {
      enabled: env.SEND_TWILIO,
      accountSid: env.TWILIO_ACCOUNT_SID,
      authToken: env.TWILIO_AUTH_TOKEN,
      from: env.TWILIO_FROM,
    },
  };
});

Add the module into the imports of the app moudle.

import { NotificationsModule } from 'src/common/notifications';

NotificationsModule.forRoot(notifications)

Default Environment variables

SEND_PUSH=1
FIREBASE_CREDENTIAL_JSON=<{Firebase credential json}>
FIREBASE_PARALLEL_LIMIT=3
SEND_EMAILS=1
EMAIL_HOST=<smtp host>
EMAIL_SMPT_PORT=<smtp port>
EMAIL_USER=<email use>
EMAIL_PASSWORD=<email password>
EMAIL_TEMPLATES_PATH='../../../templates/emails'
TWILIO_ACCOUNT_SID=<Twilio account sid>
TWILIO_AUTH_TOKEN=<Twilio auth token>
TWILIO_FROM=<Twilio from number>
SEND_TWILIO=1
SLACK_APP_TOKEN=<Slack app token>
SLACK_ALERTS_CHANNEL_ID=<Slack app channel id>
SEND_SLACK=1

Usage

Set the service as a module's provider

...
import {
  NOTIFICATION_SERVICE_TOKEN,
  NotificationsService,
} from '@globaluy/notifications';

@Module({
  providers: [
    ...
    {
      provide: NOTIFICATION_SERVICE_TOKEN,
      useClass: NotificationsService,
    },
  ],
  imports: [],
  exports: [...],
})
export class Module {}

Import it

import { NotificationsService } from "@globaluy/notifications";

Inject NotificationsService dependency.

constructor(
    private notificationsService: NotificationsService,
    ...
  ) {}

Create notification message and invoke create or createAndSendImmediately.

const notification = {
  subject: this.options.mailNewUserSubject,
  to: user.email,
  template: this.options.mailNewUserTemplate,
  context: JSON.stringify({
    fullName: `${user.firstName} ${user.lastName}`,
    email: user.email,
    url,
    currentYear: new Date().getFullYear(),
    urlLogo: `${this.options.publicAssets}/${this.options.logoName}`,
  }),
};
return this.notificationsService.createAndSendImmediately(notification);

SLACK

Sample message

const message = {
  channelId: "<channel id>",
  title: "Cars Database Appointment Service",
  description: "esto es una prueba",
  moreInfo: "y esto es mas info.",
  type: NotificationAlertType.WARN,
  values: {
    Cause: "Cannot create appointment",
    StatusCode: "BAD REQUEST",
  },
};

slack settings

A bot needs to be created, and from there we could get the token value The bot needs to be added to the channel we pretend to send messages to. We get channel id from the channel info modal in slack

NOTIFICATION KINDS

export enum NotificationKind {
  EMAIL = 'email',
  PUSH = 'push',
  PUSH_TOKEN = 'push-to-token',
  SLACK = 'slack',
  SMS = 'sms',
}

Notifications samples.

const mailNotificationToSend = {
  to: "<destination email>",
  subject: "test",
  template: "default",
  context: JSON.stringify({ body: "nuevo sms desde app" }),
};
const slackNotificationToSend = {
  to: "<channel id>",
  subject: "test",
  template: "default",
  kind: NotificationKind.SLACK,
  context: JSON.stringify({
    title: "nuevo slack desde app",
    description: "description",
    moreInfo: "y esto es mas info.",
    type: NotificationAlertType.WARN,
    values: {
      Cause: "Cannot create appointment",
      StatusCode: "BAD REQUEST",
    },
  }),
};

const smsNotificationToSend = {
  to: "<phone number>",
  kind: NotificationKind.SMS,
  context: JSON.stringify({ body: "nuevo sms desde app" }),
};

NOTIFICATION SERVICE INTERFACE

export interface INotificationsService {
  findOne(options: any): Promise<NotificationDto>;
  findAll(options: any): Promise<NotificationDto[]>;
  findAllAndCount(options: any): Promise<[NotificationDto[], number]>;
  create(notification: DeepPartial<NotificationDto>): Promise<NotificationDto>;
  createAndSendImmediately(
    notification: DeepPartial<NotificationDto>,
  ): Promise<NotificationDto>;
  update(id: number, notification: DeepPartial<NotificationDto>);
  delete(id: number);
  executeScheduler();
}