Created
April 4, 2024 13:02
-
-
Save hicglobalsolutions/fd5f254818a210067c3d133d95d7ac6d to your computer and use it in GitHub Desktop.
Now one of the most crucial parts of this component to create a new file called app.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import necessary libraries | |
var express = require('express'); // Express.js for building the server | |
var bodyParser = require('body-parser'); // Body-parser for parsing the request body | |
var cors = require('cors'); // CORS for handling cross-origin requests | |
// Import the Google Cloud client library | |
const {PubSub} = require('@google-cloud/pubsub'); // Google Cloud Pub/Sub for real-time messaging | |
// Initialize Express.js | |
var app = express(); | |
app.use(cors()); // Use CORS middleware | |
app.use(bodyParser.json()); // Use body-parser middleware to parse JSON request body | |
app.use(bodyParser.urlencoded({ extended: true })); // Parse URL-encoded bodies | |
// Initialize Google Cloud Pub/Sub client | |
const pubSubClient = new PubSub(); | |
// Define your Google Cloud Pub/Sub topic | |
const topicName = '<Replace with your topic name>'; | |
// Define POST route for '/saveData' | |
app.post('/saveData', function(req, res) { | |
let data = req.body; | |
// Convert data object to JSON string | |
let dataString = JSON.stringify(data); | |
// Function to publish message to Google Cloud Pub/Sub | |
async function publishMessage() { | |
try { | |
// Convert string to buffer | |
const dataBuffer = Buffer.from(dataString); | |
// Publish buffer to Google Cloud Pub/Sub | |
const messageId = await pubSubClient.topic(topicName).publish(dataBuffer); | |
console.log(`Message ${messageId} published.`); | |
res.status(200).json({message: 'Data published successfully'}); | |
} catch (error) { | |
console.error(`Received error while publishing: ${error.message}`); | |
// Send error response | |
res.status(500).json({message: 'Internal Server Error', error: error}); | |
} | |
} | |
// Call the publish function | |
publishMessage().catch(console.error); | |
}); | |
// Define GET route for '/' | |
app.get('/', function(req, res) { | |
res.send('Hello, World! Welcome'); | |
}); | |
// Start the server | |
app.listen(3000, function() { | |
console.log('Server listening on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment