@morphsync/event
v1.1.1
Published
A lightweight event handler for sending HTTP notifications with dynamic placeholder replacement
Readme
@morphsync/event
A lightweight event handler for sending HTTP notifications with dynamic placeholder replacement and multi-recipient support.
Features
- Send HTTP notifications to multiple recipients
- Dynamic placeholder replacement with {{variable}} syntax
- Support for nested object properties
- Built on Axios for reliable HTTP requests
- Promise-based async/await API
- Custom headers support
- Support for GET, POST, PUT, DELETE methods
- TypeScript-friendly
Installation
npm install @morphsync/eventQuick Start
const Event = require('@morphsync/event');
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestData: {
message: 'Hello {{name}}, your order {{orderId}} is ready!'
},
eventData: [
{ name: 'John', orderId: '12345' },
{ name: 'Jane', orderId: '67890' }
]
});
const responses = await event.handleEvent();
console.log(responses);Usage
Basic Notification
const Event = require('@morphsync/event');
const event = new Event({
eventRequestUrl: 'https://api.example.com/webhook',
eventRequestType: 'POST',
eventRequestData: {
title: 'New User Registration',
message: 'User {{email}} has registered'
},
eventData: [
{ email: '[email protected]' },
{ email: '[email protected]' }
]
});
await event.handleEvent();With Custom Headers
const Event = require('@morphsync/event');
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestHeaders: {
'Authorization': 'Bearer your-token-here',
'X-Custom-Header': 'custom-value'
},
eventRequestData: {
message: 'Payment of ${{amount}} received from {{customerName}}'
},
eventData: [
{ amount: 99.99, customerName: 'John Doe' }
]
});
await event.handleEvent();Nested Object Properties
const Event = require('@morphsync/event');
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestData: {
message: 'Hello {{user.firstName}} {{user.lastName}}',
email: '{{user.contact.email}}',
phone: '{{user.contact.phone}}'
},
eventData: [
{
user: {
firstName: 'John',
lastName: 'Doe',
contact: {
email: '[email protected]',
phone: '+1234567890'
}
}
}
]
});
await event.handleEvent();Email Notification Example
const Event = require('@morphsync/event');
const event = new Event({
eventRequestUrl: 'https://api.sendgrid.com/v3/mail/send',
eventRequestType: 'POST',
eventRequestHeaders: {
'Authorization': 'Bearer YOUR_SENDGRID_API_KEY'
},
eventRequestData: {
personalizations: [{
to: [{ email: '{{email}}' }],
subject: 'Welcome {{name}}'
}],
from: { email: '[email protected]' },
content: [{
type: 'text/plain',
value: 'Hello {{name}}, welcome to our platform!'
}]
},
eventData: [
{ name: 'John', email: '[email protected]' },
{ name: 'Jane', email: '[email protected]' }
]
});
await event.handleEvent();Database Integration
const Event = require('@morphsync/event');
const { MySQL } = require('@morphsync/mysql-db');
async function sendOrderNotifications() {
const db = new MySQL();
await db.connect();
const orders = await db.table('orders')
.where('status', 'pending')
.where('notified', '0')
.get();
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestData: {
orderId: '{{orderId}}',
customerName: '{{customerName}}',
amount: '{{amount}}',
message: 'Your order {{orderId}} is being processed'
},
eventData: orders
});
const responses = await event.handleEvent();
console.log('Notifications sent:', responses.length);
await db.disconnect();
}Express Controller
const Event = require('@morphsync/event');
class NotificationController {
static async sendWelcomeEmail(req, res) {
const { users } = req.body;
try {
const event = new Event({
eventRequestUrl: process.env.EMAIL_API_URL,
eventRequestType: 'POST',
eventRequestHeaders: {
'Authorization': `Bearer ${process.env.EMAIL_API_KEY}`
},
eventRequestData: {
to: '{{email}}',
subject: 'Welcome {{name}}',
body: 'Hello {{name}}, welcome to our platform!'
},
eventData: users
});
const responses = await event.handleEvent();
res.json({ success: true, sent: responses.length });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
}
}
module.exports = NotificationController;API Reference
Constructor
new Event(event)
Creates a new Event instance.
Parameters:
event(object): Event configuration objecteventRequestUrl(string, required): The API endpoint URLeventRequestType(string, required): HTTP method (GET, POST, PUT, DELETE)eventRequestHeaders(object, optional): Custom headers for the requesteventRequestData(object|string, required): Request data with placeholderseventData(array, required): Array of objects containing replacement values
Returns: Event instance
Example:
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestData: { message: 'Hello {{name}}' },
eventData: [{ name: 'John' }]
});Methods
handleEvent()
Processes the event by sending HTTP requests for each item in eventData.
Returns: Promise - Array of responses from all requests
Example:
const responses = await event.handleEvent();
console.log(responses);Error Handling
All methods throw errors that can be caught with try-catch:
const event = new Event({
eventRequestUrl: 'https://api.example.com/notify',
eventRequestType: 'POST',
eventRequestData: { message: 'Hello {{name}}' },
eventData: [{ name: 'John' }]
});
try {
const responses = await event.handleEvent();
console.log('Success:', responses);
} catch (error) {
if (error.response) {
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
} else if (error.request) {
console.error('No response received');
} else {
console.error('Error:', error.message);
}
}Dependencies
- axios - Promise based HTTP client
License
ISC
Author
Morphsync
Related Packages
- @morphsync/logger - Logger utility with automatic file organization
- @morphsync/http-request - HTTP request utility
- @morphsync/mysql-db - MySQL query builder
Support
For issues and questions, please visit the GitHub repository.
