notification-services
v1.2.0
Published
Use email, sms and custom notification services for node.js application easily
Downloads
43
Maintainers
Readme
notification-service
Overview
Microservice for handling notifications to users through real time notifications, email, or SMS.
Installation
npm i notification-servicesUsage
- Create a new nodejs/reactjs Application (If you don't have one already)
- Install the notification service
npm i notification-services.
Email:
Setup connection
There are three arguments to pass in
mailConfigfunction.Email Notifications with SMTP -
- Pass type: 'smtp' as the first argument of
mailConfigfunction. - Pass second argument as an object having the corresponding
host,userandpassfor you SMTP server. - Third argument is the
callbackfunction to get the response back. callbackwill return atransportas a response along with the message that whether the connection is setup or not.
mailConfig('smtp', { host: process.env.SMTP_HOST, user: process.env.USER, pass: process.env.PASS, }, callback);- Pass type: 'smtp' as the first argument of
Email Notifications with SES -
- Pass type: 'ses' as the first argument of
mailConfigfunction. - Pass second argument as an object having the corresponding
awsAccessId,awsAccessKey,regionandapiVersionfor you SES server. - Third argument is the
callbackfunction to get the response back.
mailConfig('smtp', { awsAccessId: process.env.AWS_ACCESS_ID, awsAccessKey: process.env.AWS_ACCESS_KEY, region: process.env.REGION, apiVersion: process.env.API_VERSION }, callback);- Pass type: 'ses' as the first argument of
Send Mail
- There are four arguments to pass in
sendMailfunction. - The first argument is
transportwhich was returned from themailConfigfunction. - Then pass
mailOptionsas the second argument.mailOptionsincludefrom,to,cc,bcc,subject,text,html, andattachments. - Third argument is
isTemplatewhich is a boolean that whether you are using any template as mail body. - Fourth and last argument is the
callbackfunction to get the response back.
sendMail(
transporter,
data: {
from, // sender address
to, // list of receivers
cc?, // list of cc
bcc?, // list of bcc
subject?, // Subject line
text?, // plain text body
html?, // html body
attachments?: {
filename?: string | false;
cid?: string;
encoding?: string;
contentType?: string;
contentTransferEncoding?: '7bit' | 'base64' | 'quoted-printable' | false;
contentDisposition?: 'attachment' | 'inline';
headers?: Headers;
raw?: string | Buffer | Readable | {
content?: string | Buffer | Readable;
path?: string | Url;
};
}[]
},
isTemplate,
callback
);If isTemplate is false, the sendMail funtion will send the mail to the respective recievers with the body of mail provided in the data.
But if isTemplate is true, the sendMail will return an email of type (Email) which can be used to send mail as follows:
email.send({
template,
locals
})
.then((response: any) => {
console.log(response);
})
.catch((error: any) => {
console.log(error);
});
}In the above code, the template is the name of template which you are using and the locals are the variables which were there in the template.
For more information on email.send function refer email-templates (npm)
SMS:
There are three arguments to pass in
SMSSendfunction.SMS Notifications with Gupshup -
- Pass type: 'gupshup' as the first argument of
SMSSendfunction. - Pass second argument as an object having the configurations:
appid,apiKey,toandmessage. - Third argument is the
callbackfunction to get the response back.
SMSSend('gupshup', { appid: process.env.APP_ID, apiKey: process.env.API_KEY, to, // recievers message, // notification to be sent in SMS }, callback);- Pass type: 'gupshup' as the first argument of
SMS Notifications with Fast2sms -
- Pass type: 'fast2sms' as the first argument of
SMSSendfunction. - Pass second argument as an object having the configurations:
senderID,apiKey,fast2smsRoute,toandmessage. - Third argument is the
callbackfunction to get the response back.
SMSSend('fast2sms', { fast2smsRoute: process.env.FAST_2_SMS_ROUTE, apiKey: process.env.API_KEY, senderID: process.env.SENDER_ID, to, // recievers message, // notification to be sent in SMS }, callback);- Pass type: 'fast2sms' as the first argument of
SMS Notifications with Messagebird -
- Pass type: 'messagebird' as the first argument of
SMSSendfunction. - Pass second argument as an object having the corresponding
from,apiKey,toandmessagefor you SMTP server. - Third argument is the
callbackfunction to get the response back.
SMSSend('messagebird', { from, // sender's name apiKey: process.env.API_KEY, to, // recievers message, // notification to be sent in SMS }, callback);- Pass type: 'messagebird' as the first argument of
SMS Notifications with Twilio -
- Pass type: 'twilio' as the first argument of
SMSSendfunction. - Pass second argument as an object having the corresponding
twilioAccountSid,twilioAuthToken,toandmessagefor you SMTP server. - Third argument is the
callbackfunction to get the response back.
SMSSend('twilio', { twilioAccountSid: process.env.TWILIO_ACCOUNT_SID, twilioAuthToken: process.env.TWILIO_AUTH_TOKEN, from, // sender's name to, // recievers message, // notification to be sent in SMS }, callback);- Pass type: 'twilio' as the first argument of
Custom Notification (Legacy - Deprecated):
⚠️ This method uses the legacy FCM API and is deprecated. Please use the new FCM v1 API below for new projects.
- There are two arguments to pass in
sendCustomNotificationfunction. - Pass
optionsas the first argument.optionsincludeserverKey,title,textandfcm_tokens. - Second argument is the
callbackfunction to get the response back.
sendCustomNotification({
serverKey: process.env.SERVER_KEY,
title, // title of notification
text, // content
fcm_tokens, // recievers' fcm tokens
}, callback);Firebase Cloud Messaging (FCM) v1 API:
The new FCM v1 API provides enhanced security with OAuth2 authentication and more flexible message targeting.
Setup FCM Configuration
import { fcmConfig } from 'notification-services';
// Configure with service account key file
fcmConfig({
projectId: 'your-firebase-project-id',
serviceAccountKey: './path/to/service-account-key.json'
});
// Or configure with environment variables
fcmConfig({
projectId: process.env.FCM_PROJECT_ID,
serviceAccountKey: {
type: "service_account",
project_id: process.env.FCM_PROJECT_ID,
private_key_id: process.env.FCM_PRIVATE_KEY_ID,
private_key: process.env.FCM_PRIVATE_KEY?.replace(/\\n/g, '\n'),
client_email: process.env.FCM_CLIENT_EMAIL,
client_id: process.env.FCM_CLIENT_ID,
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_x509_cert_url: process.env.FCM_CLIENT_CERT_URL
}
});Send to Single Device
import { fcmSendToToken } from 'notification-services';
const result = await fcmSendToToken('device-token', {
notification: {
title: 'Hello World',
body: 'This is a test notification'
},
data: {
userId: '123',
action: 'open_chat'
},
webpush: {
fcm_options: {
link: '/chat'
},
notification: {
icon: '/icon-192x192.png'
}
}
});Send to Multiple Devices
import { fcmSendMulticast } from 'notification-services';
const tokens = ['token1', 'token2', 'token3'];
const result = await fcmSendMulticast(tokens, {
notification: {
title: 'Broadcast Message',
body: 'This goes to multiple devices'
}
});
console.log(`Success: ${result.successCount}, Failed: ${result.failureCount}`);Send to Topic
import { fcmSendToTopic } from 'notification-services';
await fcmSendToTopic('news', {
notification: {
title: 'Breaking News',
body: 'Important news update'
}
});Platform-Specific Configurations
const message = {
notification: {
title: 'Cross-platform title',
body: 'Cross-platform message'
},
android: {
priority: 'high',
notification: {
color: '#ff0000',
sound: 'default',
channel_id: 'important'
}
},
apns: {
payload: {
aps: {
badge: 1,
sound: 'default'
}
}
},
webpush: {
notification: {
icon: '/icon.png',
requireInteraction: true
},
fcm_options: {
link: '/notification-page'
}
}
};
await fcmSendToToken('device-token', message);For detailed migration guide and advanced usage, see FCM v1 Migration Guide.
- Start the application
npm start
API Documentation
Common Headers
Content-Type: application/json in the response and in request if the API method is NOT GET
Common Responses
200: Successful Response. Response body varies w.r.t API 401: Unauthorized: The JWT token is missing or invalid 403: Forbidden : Not allowed to execute the concerned API 404: Entity Not Found 400: Bad Request (Error message varies w.r.t API) 201: No content: Empty Response
License
MIT
API's Details
Visit the Abstraction Layer
