Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xprilion
Created April 13, 2023 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xprilion/b2b763e11c3d4a51a90e2dfa8f49210d to your computer and use it in GitHub Desktop.
Save xprilion/b2b763e11c3d4a51a90e2dfa8f49210d to your computer and use it in GitHub Desktop.
Here's a sample Node.js Cloud Function called processData that handles real-time data processing for inventory management. In this example, we assume that the inventory data is stored in a Firestore database and the Cloud Function is triggered by a Cloud Pub/Sub message containing the product ID and the change in quantity.
const { Firestore } = require('@google-cloud/firestore');
const firestore = new Firestore();
const INVENTORY_COLLECTION = 'inventory';
async function updateInventory(productId, quantityChange) {
const productRef = firestore.collection(INVENTORY_COLLECTION).doc(productId);
try {
await firestore.runTransaction(async (transaction) => {
const productSnapshot = await transaction.get(productRef);
if (!productSnapshot.exists) {
console.error(`Product not found: ${productId}`);
return;
}
const currentQuantity = productSnapshot.data().quantity;
const newQuantity = currentQuantity + quantityChange;
if (newQuantity < 0) {
console.error(`Insufficient stock for product: ${productId}`);
return;
}
transaction.update(productRef, { quantity: newQuantity });
console.log(`Updated inventory for product ${productId}: ${newQuantity}`);
});
} catch (error) {
console.error(`Error updating inventory: ${error}`);
}
}
exports.processData = async (message, context) => {
const messageData = JSON.parse(Buffer.from(message.data, 'base64').toString());
const productId = messageData.productId;
const quantityChange = messageData.quantityChange;
if (!productId || typeof quantityChange !== 'number') {
console.error('Invalid message data');
return;
}
await updateInventory(productId, quantityChange);
};
{
"name": "inventory-management",
"version": "1.0.0",
"dependencies": {
"@google-cloud/firestore": "^4.13.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment