1.1.6 • Published 10 months ago

@therocketcodemx/library-notifications v1.1.6

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

@therocketcodemx/library-notifications

:rocket: Table of Contents :rocket:

Install

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js. Node.js 0.6 or higher is required.

Installation is done using the npm install command:

$ npm install @therocketcodemx/library-notifications

Introduction

This is a notification library for Node.js. It provides services to send notifications using popular service providers such as Mailjet, Sendgrid and Firebase. This library is designed to abstract away the complexities of integrating with various email providers and gives you a simple interface to work with.

Usage

Here's a brief description of each service:

MailjetEmailService

MailjetEmailService is a class in this library that provides an easy-to-use interface for sending emails using the Mailjet service. This class includes several methods for sending and formatting your emails, as well as handling any errors that may occur.

// Example usage
const {
  MailjetEmailService,
} = require('@therocketcodemx/library-notifications');

// Initialize the service with your Mailjet API key and secret
const mailjet = new MailjetEmailService({
  apiKey: 'your-mailjet-api-key',
  apiSecret: 'your-mailjet-api-secret',
});

// Define your email parameters
const emailParams = {
  From: { Email: 'sender@example.com', Name: 'Sender' },
  To: [{ Email: 'recipient@example.com', Name: 'Recipient' }],
  Subject: 'Test Email',
  TextPart: 'This is a test email',
  HTMLPart: '<h1>This is a test email</h1>',
  TemplateID: 123456,
  TemplateLanguage: true,
  Variables: { day: 'Monday' },
};

// Send the email
mailjet
  .sendEmail(emailParams)
  .then((response) => console.log(response.body))
  .catch((err) => console.log(err.message));

constructor(credentials: MailjetCredentials) Creates a new MailjetEmailService instance.

credentials: MailjetCredentials: An object containing the API key and secret for Mailjet. sendEmail(params: MailjetEmailParams): Promise<LibraryResponse>

Sends an email. Returns a promise that resolves to the Mailjet response.

params: MailjetEmailParams: An object containing the parameters for the email to be sent. This includes the sender's information, recipients' information, the subject, body text, HTML content, and optional attachments, among other things.

MailjetEmailParams Interface

MailjetEmailParams is an interface for the parameters of a Mailjet email. This includes details about the sender and recipients, the subject and content of the email, any attachments, and various optional settings.

MailjetEmailParams Properties

  • From (Object): This is an object that specifies the sender's information. It must include an Email field for the sender's email address, and it can optionally include a Name field for the sender's name. Example: From: { Email: 'example@example.com', Name: 'John Doe' }
  • To (Array): This is an array of objects, each specifying a recipient's information. Each object must include an Email field for the recipient's email address, and it can optionally include a Name field for the recipient's name. Example: To: [ { Email: 'recipient1@example.com', Name: 'Recipient One' }, { Email: 'recipient2@example.com', Name: 'Recipient Two' } ]
  • Cc (Array, optional): This is an array of objects, each specifying a CC recipient's information. Each object must include an Email field for the recipient's email address, and it can optionally include a Name field for the recipient's name. Example: Cc: [ { Email: 'ccrecipient1@example.com', Name: 'CC Recipient One' } ]
  • Bcc (Array, optional): This is an array of objects, each specifying a BCC recipient's information. Each object must include an Email field for the recipient's email address, and it can optionally include a Name field for the recipient's name. Example: Bcc: [ { Email: 'bccrecipient1@example.com', Name: 'BCC Recipient One' } ]
  • Subject (String): This is the subject line of the email. Example: Subject: 'Email Subject Line'
  • TextPart (String, optional): This is the plain text content of the email. If HTMLPart is also provided, recipients will be able to view the email in either plain text or HTML based on their email client's settings. If HTMLPart is not provided, then TextPart is required. Example: TextPart: 'This is the plain text content of the email.'
  • HTMLPart (String, optional): This is the HTML content of the email. If TextPart is also provided, recipients will be able to view the email in either plain text or HTML based on their email client's settings. If TextPart is not provided, then HTMLPart is required. Example: HTMLPart: '<h1>This is the HTML content of the email.</h1>'
  • Attachments (Array, optional): This is an array of objects, each specifying an attachment. Each object must include a ContentType field for the attachment's MIME type, a Filename field for the attachment's filename, and a Base64Content field for the base64-encoded content of the attachment. Example: Attachments: [ { ContentType: 'application/pdf', Filename: 'file.pdf', Base64Content: 'Base64 encoded content of the file' } ]
  • InlinedAttachments (Array, optional): This is an array of objects, each specifying an inline attachment. Each object must include a ContentType field for the attachment's MIME type, a Filename field for the attachment's filename, a Base64Content field for the base64-encoded content of the attachment, and a ContentID field that matches a 'cid:ContentID' in the HTML part of the email. Example: InlinedAttachments: [ { ContentType: 'image/png', Filename: 'image.png', Base64Content: 'Base64 encoded content of the image', ContentID: 'image1' } ]
  • Globals (Object, optional): An object to specify properties that will be applied to all message objects when sending messages in bulk. You can specify values for all message properties except To. Example: Globals: { Subject: 'Global Subject', TextPart: 'This is a global text part' }
  • TemplateID (Number, optional): This is an ID for a template that is previously created and stored in Mailjet's system. It is required when From and TextPart and/or HTMLPart are not provided. Example: TemplateID: 12345
  • TemplateLanguage (Boolean, optional): This is a flag that indicates whether the template language is used. Example: TemplateLanguage: true
  • Variables (Object, optional): An object of variables for the template. By using Variables in conjunction with the {{var:VAR_NAME}} or {{var:VAR_NAME:DEFAULT_VALUE}} , you can modify the content of your email with variables, pushed in your Send API call. Example: Variables: { day: 'Monday' }
  • CustomID (String, optional): This is a custom ID for the message. You can use your own ID to easily trace back the message in the system. Example: CustomID: 'custom123'
  • Headers (Object, optional): An object of custom headers for the message. These headers will be added to the SMTP headers of the message, delivered to the recipient. Example: Headers: { 'X-Custom-Header': 'CustomHeaderValue' }
  • EventPayload (String, optional): This is a payload for the event. You can insert a payload in the message which can be of any format (XML, JSON, CSV, etc). Example: EventPayload: 'Custom event payload'
  • CustomCampaign (String, optional): A custom campaign name. Use this property to specify the name of the campaign the message will be classified in. Example: CustomCampaign: 'My Custom Campaign'
  • DeduplicateCampaign (Boolean, optional): Indicates if deduplication should be turned off for the campaign. Example: DeduplicateCampaign: true
  • URLTags (String, optional): This property is used to add tracking parameters in all your URLs in your message. Example: URLTags: 'utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale'
  • SandboxMode (Boolean, optional): If true, the email will be validated but not sent. Example: SandboxMode: true

For a full list of fields and their explanations, refer to the source code documentation or the Mailjet API documentation.

SendgridEmailService

SendgridEmailService is a class in this library that provides a simplified interface for sending emails using the Sendgrid service. This class offers several methods for sending, formatting emails, and handling any errors that might occur.

// Example usage
const {
  SendgridEmailService,
} = require('@therocketcodemx/library-notifications');

// Initialize the service with your Sendgrid API key
const sendgrid = new SendgridEmailService('your-sendgrid-api-key');

// Sending a plain text email
// Define your email parameters
const emailParams = {
  to: { email: 'recipient@example.com', name: 'Recipient' },
  from: { email: 'sender@example.com', name: 'Sender' },
  subject: 'Hello, World!',
  text: 'Hello, this is a test email.',
};

// Sending an HTML email
const emailParams = {
  to: { email: 'recipient@example.com' },
  from: { email: 'sender@example.com' },
  subject: 'Hello World',
  html: '<p>This is a test email</p>',
};

// Sending an email using a template
const emailParams = {
  to: { email: 'recipient@example.com' },
  from: { email: 'sender@example.com' },
  templateId: 'd-12345678901234567890123456789012',
  dynamicTemplateData: { firstName: 'John', lastName: 'Doe' },
};

// Send the email
sendgrid
  .sendEmail(emailParams)
  .then((response) => console.log(response.body))
  .catch((err) => console.log(err.message));

// Or, to send multiple emails at once, you can pass an array of email parameters
const multipleEmailParams = [
  {
    to: { email: 'recipient1@example.com', name: 'Recipient 1' },
    from: { email: 'sender@example.com', name: 'Sender' },
    subject: 'Hello, Recipient 1!',
    text: 'This is a test email for Recipient 1.',
  },
  {
    to: { email: 'recipient2@example.com', name: 'Recipient 2' },
    from: { email: 'sender@example.com', name: 'Sender' },
    subject: 'Hello, Recipient 2!',
    text: 'This is a test email for Recipient 2.',
  },
];
sendgrid
  .sendEmail(multipleEmailParams)
  .then((response) => console.log(response.body))
  .catch((err) => console.log(err.message));

API

constructor(apiKey: string) Creates a new SendgridEmailService instance.

apiKey: string: The API key for Sendgrid.

sendEmail(params: SendgridEmailParams | SendgridEmailParams[]): Promise<client.ClientResponse>

Sends an email or multiple emails. Returns a promise that resolves to the Sendgrid client response.

params: SendgridEmailParams | SendgridEmailParams[]: An object or array of objects containing the parameters for the email(s) to be sent. This includes the sender's information, recipients' information, the subject, body text, HTML content, and optional attachments, among other things.

SendgridEmailParams Interface

SendgridEmailParams is an interface for the parameters of a Sendgrid email. This includes details about the sender and recipients, the subject and content of the email, any attachments, and various optional settings.

Properties

  • to (Object | Array): The recipient(s) of the email. Each EmailData object should include an email string and may optionally include a name string. Example: to: { name: 'Recipient', email: 'recipient@example.com' }
  • from (Object): The sender of the email. It should be an EmailData object. Example: from: { name: 'Sender', email: 'sender@example.com' }
  • replyTo (Object): Reply-to email address. It should be an EmailData object. Example: replyTo: { name: 'Replier', email: 'replier@example.com' }
  • cc (Object | Array): An array of recipients who will receive a copy of your email. Example: cc: [ { name: 'Recipient 1', email: 'recipient1@example.com' }, { name: 'Recipient 2', email: 'recipient2@example.com' }, ]
  • bcc (Object | Array): An array of recipients who will receive a blind carbon copy of your email. Example: bcc: [ { name: 'Recipient 1', email: 'recipient1@example.com' }, { name: 'Recipient 2', email: 'recipient2@example.com' }, ]
  • subject (String): The subject line of the email. Example: subject: 'Hello World'
  • text (String): The plain text content of the email. Example: text: 'This is a test email'
  • html (String): The HTML content of the email. Example: html: '<p>This is a test email</p>'
  • content (Array): An array where you can specify the content of your email. You can include multiple MIME types of content. Example: content: [ { type: 'text/plain', value: 'This is a test email' }, { type: 'text/html', value: '<p>This is a test email</p>' }, ]
  • templateId (String): The ID of the template to use. Example: templateId: 'd-12345678901234567890123456789012'
  • personalizations (Array): Array of personalization blocks. Each PersonalizationData object can contain recipients (to, cc, bcc), subject, headers, substitutions, dynamicTemplateData, customArgs and sendAt. Example: personalizations: [ { to: [{ email: 'recipient1@example.com' }], cc: [{ email: 'recipient2@example.com' }], subject: 'Hello, Recipient 1', }, { to: [{ email: 'recipient3@example.com' }], subject: 'Hello, Recipient 3', }, ]
  • attachments (Array): An array of attachments. Each SendgridAttachment object should include a content string (Base64 encoded), filename string, and may optionally include type (MIME type), disposition, and contentId. Example: attachments: [ { content: 'Base64 encoded content', filename: 'example.txt', type: 'plain/text', disposition: 'attachment', contentId: 'contentID', }, ]
  • ipPoolName (String): The IP Pool that should be used for the email. Example: ipPoolName: 'IP Pool Name'
  • batchId (String): Batch ID for grouping events in SendGrid's Event Webhook. Example: batchId: 'QWU0NzgxYzUtMjkzZSDAwNjVjZGU0LWNiODk2MDliZR'
  • sections (Object): Sections for substitutions in the email template. Example: sections: { '%section1%': 'Substitution for section 1' }
  • headers (Object): Additional headers to add to the email. Example: headers: { 'X-Custom-Header': 'Custom header value' }
  • categories (Array): Categories to categorize the email. Example: categories: ['Category1', 'Category2']
  • category (String): Category to categorize the email. Example: category: 'Category'
  • customArgs (Object): Custom arguments that are specific to this email. Example: customArgs: { 'arg1': 'value1' }
  • asm An object allowing you to specify how to handle unsubscribes. Example: asm: { groupId: 1, groupsToDisplay: [1, 2, 3] }
  • mailSettings (Object): A collection of different mail settings. Example: mailSettings: { bcc: { enable: true, email: 'bcc@example.com' }, footer: { enable: true, text: 'Footer Text', html: '<p>Footer HTML</p>' } }
  • trackingSettings (Object): Settings to determine how you would like to track the metrics of how your recipients interact with your email. Example: trackingSettings: { clickTracking: { enable: true, enableText: true }, openTracking: { enable: true, substitutionTag: '%opentrack%' } }
  • substitutions (Object): Substitutions to apply to the email. Example: substitutions: { '%name%': 'User' }
  • substitutionWrappers (Array): Wrapper strings to define substitution sections. substitutionWrappers: ['%', '%']
  • isMultiple (Boolean): If the email has multiple recipients. Example: isMultiple: true
  • dynamicTemplateData (Object): Data for SendGrid's dynamic templates. Example: dynamicTemplateData: { 'variable': 'value' }
  • hideWarnings (Boolean): If warnings should be hidden. Example: hideWarnings: false
  • replyToList (Array or Object): An array or a single object of recipients who will receive replies and/or bounces. Each object in this array or the single object must contain the recipient's email address. Each object in the array or the single object may optionally contain the recipient's name. You can either choose to use reply_to field or reply_to_list but not both. Example with single recipient: replyToList: { name: 'John Doe', email: 'john@example.com' } Example with multiple recipients: replyToList: [ { name: 'John Doe', email: 'john@example.com' }, { name: 'Jane Doe', email: 'jane@example.com' } ]. This replyToList property is particularly useful if you need to send reply emails or bounce notifications to different addresses.

For a full list of fields and their explanations, refer to the source code documentation or the Sendgrid API documentation.

sendPushNotification

sendPushNotification, this function is used to send notifications through the web. Below is an example of use:

import {
  sendPushNotification,
  IPushNotification
} = from '@therocketcodemx/library-notifications';
const pathServiceAccount: string = '../../rocket-3c003-firebase-adminsdk-xmfpn-4c78501871.json'
//from the same library you can import the types of data that the function receives
const input: IPushNotification = {
    notification: {
        title: 'The rocket code'; // Title of message
        body: 'Hello world'; // Body of message
    }
    token: 'YOUR-TOKEN'; // you can get the token directly in your firebase project.
}
const sendNotification = async () => {
  const response = await sendPushNotification(input, pathServiceAccount)
  //example response
  const { failureCount, responses, successCount } = response;
  // success
  // responses.success === true
  // fail
  // responses.success === false
  // responses.error === 'FirebaseError'
}

sendTextMessage

This function is used to send text messages through the WhatsApp API. Below is an example of use:

import {
  sendTextMessage,
  ISendMessage
} = from '@therocketcodemx/library-notifications';
const message: ISendMessage = {
    messaging_product: 'whatsapp'; //por default se envía "whatsapp"
    to: '525533111999'; // country code (52) + phone number (5533111999)
    type: 'text'; // only have text type
    text: {
        body: 'Hello world';
    }
}
const phoneNumberId: number = '1231425354353'; // This Id is obtained from the platform where the application was created created in meta developers.
const token: string = 'YOUR-TOKEN' // This TOKEN is obtained from the platform where the application was created in meta developers.
const sendMessage = async () => {
  const response = await sendTextMessage(message, phoneNumberId, token); // Returns true if successful, false otherwise.
}

TwilioSMSService

TwilioSMSService is a class in this library that provides a simple interface for sending SMS messages using the Twilio service. This class includes methods for sending your messages and handling any errors that may occur.

// Example usage
import { TwilioSMSService } from '@therocketcodemx/library-notifications';

// Initialize the service with your Twilio account SID and auth token
const twilioCredentials = {
  accountSid: 'your-twilio-account-sid',
  authToken: 'your-twilio-auth-token',
};

const twilioService = new TwilioSMSService(twilioCredentials);

// Define your SMS parameters
const smsParams = {
  body: 'Hello, this is a test message',
  to: '+1234567890', // recipient's phone number
  from: '+0987654321', // your Twilio phone number
};

// Send the SMS
try {
  const result = await twilioService.sendSMS(smsParams);
  console.log(result);
} catch (error) {
  console.error(error);
}

API

constructor(credentials) Creates a new TwilioSMSService instance.

credentials: An object containing the account SID and auth token for Twilio.

sendSMS(params): Promise<MessageInstance>

Sends an SMS message. Returns a promise that resolves to the Twilio message instance.

params: An object containing the parameters for the SMS to be sent. This includes the body of the message, the recipient's phone number, and your Twilio phone number.

1.1.6

10 months ago

1.1.5

10 months ago

1.1.4

10 months ago

1.1.3

10 months ago

1.1.2

11 months ago

1.1.1

11 months ago

1.1.0

11 months ago

1.0.15

11 months ago

1.0.14

11 months ago

1.0.13

11 months ago

1.0.12

11 months ago

1.0.11

11 months ago

1.0.10

11 months ago

1.0.9

11 months ago

1.0.8

11 months ago

1.0.7

11 months ago

1.0.6

11 months ago

1.0.5

11 months ago

1.0.4

11 months ago

1.0.3

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago

1.0.0

11 months ago