const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Optional: Basic authentication middleware
const basicAuth = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Basic ')) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
};
const triggerEmailNotification = async (to, data) => {
let { name, uid, email } = to;
let { groupDetails, senderDetails, subject } = data;
if (groupDetails) {
console.log('Received webhook for group email notification');
}
if (senderDetails) {
console.log('Received webhook for one-on-one email notification');
}
if (email == null) {
// Your implementation to fetch Email ID
email = await fetchEmailIDFor(uid);
}
// Your implementation for sending the email notification
await sendEmail(email, subject, data.messages);
};
app.post('/webhook', basicAuth, (req, res) => {
const { trigger, data, appId, region, webhook } = req.body;
const { to } = data || {};
if (
trigger !== 'email-notification-payload-generated' ||
webhook !== 'custom'
) {
return res.status(400).json({ message: 'Invalid trigger or webhook type' });
}
console.log('Received Webhook:', JSON.stringify(req.body, null, 2));
triggerEmailNotification(to, data)
.then((result) => {
console.log(
'Successfully triggered email notification for',
appId,
to.uid,
result
);
})
.catch((error) => {
console.error(
'Something went wrong while triggering email notification for',
appId,
to.uid,
error.message
);
});
res.status(200).json({ message: 'Webhook received successfully' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});