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 triggerPushNotification = async (to, notificationDetails) => {
const { name, uid } = to;
const { type, notificationTitle, notificationBody } = notificationDetails;
if (type == 'call') {
console.log('Push notification for calling event');
// Use the following details to send a call notification.
const { callAction, sessionId, callType } = notificationDetails;
}
if (type == 'chat') {
console.log('Push notification for messaging event');
}
const token = await fetchPushToken(uid);
// Your implementation for sending the Push notification
await sendPushNotification(token, notificationTitle, notificationBody);
};
app.post('/webhook', basicAuth, (req, res) => {
const { trigger, data, appId, region, webhook } = req.body;
const { to } = data || {};
if (
trigger !== 'push-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));
triggerPushNotification(to, data)
.then((result) => {
console.log(
'Successfully triggered Push notification for',
appId,
to.uid,
result
);
})
.catch((error) => {
console.error(
'Something went wrong while triggering Push 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}`);
});