-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/whatsapp #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6aadbc9
implemented decorators and providers
y-aithnini ada99be
Add notification and webhook controller tests
y-aithnini 571aecc
remove in-memory repository and update exports
y-aithnini 73009e2
removed mongoose
y-aithnini 4210d2c
Merge develop: resolve conflicts and update jest config for spec files
y-aithnini 96a80f6
removed duplicate code for sonarqube
y-aithnini aac7189
docs: add comprehensive documentation for testing implementation
y-aithnini 81e390e
style: fix prettier formatting issues
y-aithnini 746f00e
Merge branch 'develop' of https://github.com/CISCODE-MA/NotificationK…
y-aithnini 2b5c2f4
integrated whatsapp notification msg
y-aithnini 0e0de92
updated configuration
y-aithnini 804543a
fix: replace deprecated substr() with slice() in mock WhatsApp sender
y-aithnini File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,24 +1,27 @@ | ||
| # @ciscode/notification-kit | ||
|
|
||
| > A flexible, type-safe notification system for NestJS applications supporting multiple channels (Email, SMS, Push) with pluggable providers. | ||
| > A lightweight, delivery-focused notification library for NestJS. Send notifications through multiple channels (Email, SMS, Push, WhatsApp) with pluggable providers. **Your app manages content and templates, NotificationKit handles delivery.** | ||
|
|
||
| [](https://www.npmjs.com/package/@ciscode/notification-kit) | ||
| [](https://opensource.org/licenses/MIT) | ||
| [](https://www.typescriptlang.org/) | ||
|
|
||
| ## ✨ Features | ||
|
|
||
| - 🚀 **Multi-Channel Support** - Email, SMS, and Push notifications in one unified interface | ||
| - 🎯 **Lightweight & Focused** - Does one thing well: delivers notifications. No bloat, no unnecessary dependencies. | ||
| - 🚀 **Multi-Channel Support** - Email, SMS, Push, and WhatsApp notifications in one unified interface | ||
| - 🔌 **Pluggable Providers** - Support for multiple providers (Twilio, AWS SNS, Firebase, Nodemailer, etc.) | ||
| - 📱 **WhatsApp Support** - Send WhatsApp messages with media support via Twilio API | ||
| - 🎯 **NestJS First** - Built specifically for NestJS with dependency injection support | ||
| - 📦 **Framework Agnostic Core** - Clean architecture with framework-independent domain logic | ||
| - 🔄 **Retry & Queue Management** - Built-in retry logic and notification state management | ||
| - 📊 **Event System** - Track notification lifecycle with event emitters | ||
| - 🎨 **Template Support** - Handlebars and simple template engines included | ||
| - 💾 **Flexible Storage** - MongoDB, PostgreSQL, or custom repository implementations | ||
| - ✅ **Fully Tested** - Comprehensive test suite with 133+ tests | ||
| - 🔒 **Type Safe** - Written in TypeScript with full type definitions | ||
|
|
||
| > **📐 Design Philosophy**: NotificationKit is a **delivery library**, not a content management system. Your application should manage templates, content, and business logic. NotificationKit focuses solely on reliable multi-channel delivery. | ||
|
|
||
| ## 📦 Installation | ||
|
|
||
| ```bash | ||
|
|
@@ -39,6 +42,9 @@ npm install twilio # Twilio | |
| npm install @aws-sdk/client-sns # AWS SNS | ||
| npm install @vonage/server-sdk # Vonage | ||
|
|
||
| # For WhatsApp | ||
| npm install twilio # Twilio WhatsApp API | ||
|
|
||
| # For push notifications (choose one) | ||
| npm install firebase-admin # Firebase | ||
| npm install @aws-sdk/client-sns # AWS SNS | ||
|
|
@@ -148,7 +154,132 @@ POST /notifications/:id/retry | |
| POST /notifications/:id/cancel | ||
| ``` | ||
|
|
||
| ## 📚 Documentation | ||
| ## � WhatsApp Support | ||
|
|
||
| NotificationKit now supports WhatsApp messaging via Twilio's WhatsApp API with full media and template support! | ||
|
|
||
| ### Setup WhatsApp Sender | ||
|
|
||
| ```typescript | ||
| import { TwilioWhatsAppSender, MockWhatsAppSender } from "@ciscode/notification-kit"; | ||
|
|
||
| // For production (real Twilio API) | ||
| NotificationKitModule.register({ | ||
| senders: [ | ||
| new TwilioWhatsAppSender({ | ||
| accountSid: process.env.TWILIO_ACCOUNT_SID, | ||
| authToken: process.env.TWILIO_AUTH_TOKEN, | ||
| fromNumber: process.env.TWILIO_WHATSAPP_FROM, // e.g., '+14155238886' | ||
| templates: { | ||
| orderShipped: "order_shipped_v1", | ||
| welcomeMessage: "welcome_v2", | ||
| }, | ||
| }), | ||
| ], | ||
| // ... other config | ||
| }); | ||
|
|
||
| // For development/testing (no credentials needed) | ||
| NotificationKitModule.register({ | ||
| senders: [new MockWhatsAppSender({ logMessages: true })], | ||
| // ... other config | ||
| }); | ||
| ``` | ||
|
|
||
| ### Send WhatsApp Messages | ||
|
|
||
| #### Basic Text Message | ||
|
|
||
| ```typescript | ||
| await notificationService.send({ | ||
| channel: NotificationChannel.WHATSAPP, | ||
| priority: NotificationPriority.HIGH, | ||
| recipient: { | ||
| id: "user-123", | ||
| phone: "+14155551234", // E.164 format required | ||
| }, | ||
| content: { | ||
| title: "Order Update", | ||
| body: "Your order #12345 has been shipped!", | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| #### WhatsApp with Media (Images/PDFs/Videos) | ||
|
|
||
| ```typescript | ||
| await notificationService.send({ | ||
| channel: NotificationChannel.WHATSAPP, | ||
| recipient: { | ||
| id: "user-456", | ||
| phone: "+447911123456", | ||
| }, | ||
| content: { | ||
| title: "Invoice Ready", | ||
| body: "Your invoice is attached", | ||
| data: { | ||
| mediaUrl: "https://example.com/invoice.pdf", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| #### WhatsApp with Templates | ||
|
|
||
| ```typescript | ||
| await notificationService.send({ | ||
| channel: NotificationChannel.WHATSAPP, | ||
| recipient: { | ||
| id: "user-789", | ||
| phone: "+212612345678", | ||
| }, | ||
| content: { | ||
| title: "OTP Code", | ||
| body: "Your verification code is {{code}}", | ||
| templateId: "otp_verification", | ||
| templateVars: { | ||
| code: "123456", | ||
| expiryMinutes: "5", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| ### WhatsApp Requirements | ||
|
|
||
| - **Phone Format**: Must be E.164 format (`+[country code][number]`) | ||
| - ✅ Valid: `+14155551234`, `+447911123456`, `+212612345678` | ||
| - ❌ Invalid: `4155551234`, `+1-415-555-1234`, `+1 (415) 555-1234` | ||
| - **Twilio Account**: Required for production use | ||
| - **WhatsApp Opt-in**: Recipients must opt-in to receive messages (send "join [code]" to Twilio number) | ||
| - **Media Support**: Images, videos, audio, PDFs (max 16MB for videos, 5MB for images) | ||
| - **Templates**: Some message types require pre-approved WhatsApp templates | ||
|
|
||
| ### Testing WhatsApp Without Twilio | ||
|
|
||
| Use `MockWhatsAppSender` for development: | ||
|
|
||
| ```typescript | ||
| const mockSender = new MockWhatsAppSender({ logMessages: true }); | ||
|
|
||
| // Simulates sending and logs to console | ||
| // No actual API calls or credentials needed | ||
| ``` | ||
|
|
||
| Console output example: | ||
|
|
||
| ``` | ||
| ═══════════════════════════════════════════ | ||
| 📱 [MockWhatsApp] Simulating WhatsApp send | ||
| ═══════════════════════════════════════════ | ||
| To: +14155551234 | ||
| Recipient ID: user-123 | ||
|
|
||
| 💬 Message: Your order has been shipped! | ||
| ═══════════════════════════════════════════ | ||
| ``` | ||
|
|
||
| ## �📚 Documentation | ||
|
|
||
| ### Core Concepts | ||
|
|
||
|
|
@@ -157,6 +288,7 @@ POST /notifications/:id/cancel | |
| - **EMAIL** - Email notifications via SMTP providers | ||
| - **SMS** - Text messages via SMS gateways | ||
| - **PUSH** - Mobile push notifications | ||
| - **WHATSAPP** - WhatsApp messages via Twilio or Meta Business API | ||
| - **WEBHOOK** - HTTP callbacks (coming soon) | ||
|
|
||
| #### Notification Status Lifecycle | ||
|
|
@@ -188,6 +320,11 @@ CANCELLED | |
| - **AwsSnsSender** - AWS SNS for SMS | ||
| - **VonageSmsSender** - Vonage (formerly Nexmo) | ||
|
|
||
| #### WhatsApp Senders | ||
|
|
||
| - **TwilioWhatsAppSender** - Twilio WhatsApp API (supports media & templates) | ||
| - **MockWhatsAppSender** - Mock sender for testing without credentials | ||
|
|
||
| #### Push Notification Senders | ||
|
|
||
| - **FirebasePushSender** - Firebase Cloud Messaging (FCM) | ||
|
|
@@ -281,14 +418,7 @@ NotificationKitModule.registerAsync({ | |
| }), | ||
| ], | ||
| repository: new MongooseNotificationRepository(/* connection */), | ||
| templateEngine: new HandlebarsTemplateEngine({ | ||
| templates: { | ||
| welcome: { | ||
| title: "Welcome {{name}}!", | ||
| body: "Hello {{name}}, thanks for joining {{appName}}!", | ||
| }, | ||
| }, | ||
| }), | ||
| // templateEngine: optional - most apps manage templates in backend | ||
| eventEmitter: new InMemoryEventEmitter(), | ||
| }), | ||
| inject: [ConfigService], | ||
|
|
@@ -317,37 +447,74 @@ eventEmitter.on("*", (event) => { | |
| }); | ||
| ``` | ||
|
|
||
| ### Template Rendering | ||
| ### Content Management | ||
|
|
||
| > ⚠️ **Best Practice**: Manage templates and content in your backend application, not in NotificationKit. Your app knows your business logic, user preferences, and localization needs better than a delivery library. | ||
|
|
||
| **Recommended Approach** (Render in Your Backend): | ||
|
|
||
| ```typescript | ||
| import { HandlebarsTemplateEngine } from "@ciscode/notification-kit/infra"; | ||
| @Injectable() | ||
| export class NotificationService { | ||
| constructor( | ||
| private templateService: TemplateService, // Your template service | ||
| private notificationKit: NotificationService, // From NotificationKit | ||
| ) {} | ||
|
|
||
| const templateEngine = new HandlebarsTemplateEngine({ | ||
| templates: { | ||
| async sendWelcomeEmail(user: User) { | ||
| // 1. Your backend renders the template | ||
| const content = await this.templateService.render("welcome", { | ||
| name: user.name, | ||
| appName: "MyApp", | ||
| }); | ||
|
|
||
| // 2. NotificationKit delivers it | ||
| await this.notificationKit.send({ | ||
| channel: NotificationChannel.EMAIL, | ||
| recipient: { id: user.id, email: user.email }, | ||
| content: { | ||
| title: content.subject, | ||
| body: content.text, | ||
| html: content.html, | ||
| }, | ||
| }); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| **Built-in Template Engine** (Optional, for simple use cases): | ||
|
|
||
| NotificationKit includes optional template engines for quick prototyping: | ||
|
|
||
| ```typescript | ||
| import { SimpleTemplateEngine } from "@ciscode/notification-kit/infra"; | ||
|
|
||
| // Only use for demos/prototyping | ||
| NotificationKitModule.register({ | ||
| templateEngine: new SimpleTemplateEngine({ | ||
|
Comment on lines
+489
to
+494
|
||
| welcome: { | ||
| title: "Welcome {{name}}!", | ||
| body: "Hello {{name}}, welcome to {{appName}}!", | ||
| html: "<h1>Welcome {{name}}!</h1><p>Thanks for joining {{appName}}!</p>", | ||
| }, | ||
| }, | ||
| }), | ||
| }); | ||
|
|
||
| // Use in notification | ||
| // Send using template | ||
| await notificationService.send({ | ||
| channel: NotificationChannel.EMAIL, | ||
| recipient: { id: "user-123", email: "user@example.com" }, | ||
| content: { | ||
| templateId: "welcome", | ||
| templateVars: { | ||
| name: "John Doe", | ||
| appName: "My App", | ||
| }, | ||
| templateVars: { name: "John", appName: "MyApp" }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| ### Webhook Handling | ||
|
|
||
| > **Note**: Built-in templates are optional and best suited for prototyping. Production apps should manage templates in the backend for flexibility, versioning, and localization. See [Template Configuration Guide](./docs/TEMPLATE_CONFIGURATION.md) for details. | ||
|
|
||
| ```` | ||
|
|
||
|
|
||
| Enable webhook endpoints to receive delivery notifications from providers: | ||
|
|
||
| ```typescript | ||
|
|
@@ -356,7 +523,7 @@ NotificationKitModule.register({ | |
| webhookSecret: process.env.WEBHOOK_SECRET, | ||
| // ... other options | ||
| }); | ||
| ``` | ||
| ```` | ||
|
|
||
| Webhook endpoint: `POST /notifications/webhook` | ||
|
|
||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The section header contains a replacement character ("## � WhatsApp Support" / "## �📚 Documentation"), which will render incorrectly in Markdown. Replace it with a valid UTF-8 emoji/title (e.g., "## WhatsApp Support" or "## 📱 WhatsApp Support").