in reference-architectures/cloud_deploy_flow/WebsiteDemo/index.js [55:113]
async function main() {
setInterval(async () => {
for (const subscriptionName of subscriptionNames) {
await pullMessages(pubsubClient, subscriptionName);
}
}, 5000);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({extended: true})); // For parsing application/x-www-form-urlencoded
// API endpoint to send messages to the frontend
app.get('/messages', (req, res) => {
res.json(messages);
});
// Endpoint to clear all messages
app.post('/clear-messages', (req, res) => {
// Clear the messages from all subscriptions
messages = {
'build_notifications_subscription': [],
'deploy-commands-subscription': [],
'clouddeploy-operations-subscription': [],
'clouddeploy-approvals-subscription': [],
};
console.log('All messages cleared.');
res.sendStatus(200); // Respond with success
});
app.post('/send-message', async (req, res) => {
console.log(`Req Body: ${JSON.stringify(req.body, null, 2)}`);
try {
const {data, attributes} = req.body;
console.log(`Data: ${data}, Attributes: ${JSON.stringify(attributes)}`);
const topic = pubsubClient.topic(topicName);
// Create the message object with optional attributes
const dataBuf = Buffer.from('{}'); // Convert data to Buffer
// Publish the message to the Pub/Sub topic
const messageId = await topic.publish(dataBuf, attributes);
console.log(`Message sent with ID: ${messageId}`);
// Send a success response
res.status(200).send('Message published.');
} catch (error) {
console.error('Error publishing message:', error);
// Send an error response
res.status(500).send('Failed to publish message.');
}
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
}