@sonardigital/nestjs-notifications
v1.0.10
Published
NestJS module for email notifications with SendGrid, Nodemailer and Mandrill
Maintainers
Readme
Notifications Microservice
A comprehensive NestJS microservice for handling email, push, SMS, and in-app notifications with device management and user targeting capabilities.
🚀 Features
- Multiple Notification Types: Email, Push, SMS, and In-App notifications
- Device Management: Register and manage user devices with push tokens
- Multiple Email Providers: Support for SendGrid, Nodemailer, and Mandrill
- Template Engine: Handlebars template rendering for emails
- Database Integration: Prisma ORM with MongoDB support
- User Targeting: Send notifications to specific users or groups
- Health Monitoring: Built-in health check endpoints
- Swagger Documentation: Auto-generated API documentation
- Authentication: JWT-based authentication and authorization
- Validation: Comprehensive request validation with class-validator
📋 Prerequisites
- Node.js (v18 or higher)
- MongoDB database
- Email provider credentials (SendGrid, Mandrill, or SMTP)
- Push notification credentials (FCM for Android, APNS for iOS)
🛠️ Installation
- Clone the repository
git clone <repository-url>
cd nestjs-notifications- Install dependencies
npm install- Set up environment variables
cp env.example .env
# Edit .env with your configuration- Set up the database
npm run prisma:generate
npm run prisma:studio # Optional: Open Prisma Studio to view data- Start the microservice
npm run start:dev🔧 Configuration
Environment Variables
# Application Configuration
NODE_ENV=development
PORT=3001
API_PREFIX=api
CORS=true
# Database
DATABASE_URL="mongodb://localhost:27017/notifications"
# JWT
JWT_SECRET=your-super-secret-jwt-key
# Email Providers
SENDGRID_API_KEY=your-sendgrid-api-key
MANDRILL_API_KEY=your-mandrill-api-key
# SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=your-app-password
# Push Notifications
FCM_SERVER_KEY=your-fcm-server-key
APNS_KEY_ID=your-apns-key-id
APNS_TEAM_ID=your-apns-team-id
APNS_BUNDLE_ID=your-app-bundle-id
APNS_PRIVATE_KEY=your-apns-private-key
# Default Email Configuration
[email protected]📚 API Documentation
Once the service is running, access the Swagger documentation at:
http://localhost:3001/api/docsKey Endpoints
Health Checks
GET /api/health- Basic health checkGET /api/health/ready- Readiness checkGET /api/health/live- Liveness check
Device Management
POST /api/devices/register- Register a new deviceGET /api/devices/user/:userId- Get user's devicesPUT /api/devices/:id- Update device informationDELETE /api/devices/:id- Delete a device
Notifications
POST /api/notifications/send- Send a notificationPOST /api/notifications/email- Send email using templatesPOST /api/notifications/push- Send push notifications
🏗️ Architecture
Database Schema
The microservice uses MongoDB with the following main models:
- User: User information and account association
- Device: Device registration with push tokens
- Notification: Notification records and tracking
- NotificationRecipient: Individual recipient tracking
- EmailTemplate: Reusable email templates
- EmailLog: Email delivery logging
Service Structure
src/
├── config/ # Configuration files
├── constants/ # Application constants
├── decorators/ # Custom decorators
├── enums/ # TypeScript enums
├── guards/ # Authentication guards
├── interceptors/ # Response interceptors
├── modules/ # Feature modules
│ ├── app/ # Main application module
│ ├── devices/ # Device management
│ ├── health/ # Health checks
│ ├── notifications/ # Notification services
│ └── prisma/ # Database service
└── utils/ # Utility services🔐 Authentication
The microservice uses JWT-based authentication. Include the Bearer token in your requests:
curl -H "Authorization: Bearer your-jwt-token" \
-H "x-account-id: 123" \
http://localhost:3001/api/notifications/send📱 Device Management
Register a Device
POST /api/devices/register
{
"userId": "user123",
"deviceId": "device456",
"pushToken": "fcm-token-or-apns-token",
"platform": "ANDROID",
"appVersion": "1.0.0",
"isActive": true
}Send Push Notification
POST /api/notifications/push
{
"title": "New Message",
"body": "You have a new message from John",
"userIds": ["user123", "user456"],
"platform": "ANDROID",
"data": {
"messageId": "msg123",
"senderId": "user789"
}
}📧 Email Templates
Create Email Template
Templates are stored in the database and use Handlebars syntax:
<h1>Welcome {{userName}}!</h1>
<p>Thank you for joining {{appName}}.</p>
<p>Your account is now active.</p>Send Template Email
POST /api/notifications/email
{
"templateName": "welcome",
"to": ["[email protected]"],
"variables": {
"userName": "John Doe",
"appName": "MyApp"
}
}🚀 Deployment
Docker Deployment
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3001
CMD ["npm", "run", "start:prod"]Environment Setup
- Set up MongoDB cluster
- Configure environment variables
- Run database migrations
- Deploy the application
🧪 Development
Running Tests
npm run test
npm run test:watch
npm run test:covCode Quality
npm run lint
npm run format
npm run check-allDatabase Management
npm run prisma:studio # Open Prisma Studio
npm run prisma:generate # Generate Prisma client
npm run seed # Seed database with sample data📈 Monitoring
The service includes comprehensive health checks:
- Health Check: Basic service status
- Readiness Check: Database connectivity and service readiness
- Liveness Check: Service is alive and responsive
🔄 Migration from NPM Package
This microservice was converted from an NPM package. Key changes:
- Database Integration: Added Prisma ORM and MongoDB schema
- Device Management: Added device registration and push token management
- User Targeting: Added user-based notification targeting
- Microservice Architecture: Converted to standalone service with REST API
- Health Monitoring: Added health check endpoints
- Authentication: Added JWT-based authentication
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the UNLICENSED License.
