I am working on a Next JS app with Firebase and I am stuck on Firebase Cloud functions and how to retrieve data after an onCreate or onUpdate trigger. I am new to the admin SDK so pardon me if the question looks simple.
My document structure looks like this:
{
"amount" : 123,
"code" : "RAB45MGTRK",
"createdOn" : "Wed Jan 11 2023 08:34:25 GMT 0000 (Coordinated Universal Time)",
"phone" : "0700 000 000",
"rice" : "160",
"sugar" : "136",
"user_id" : "IjsdigsdTr345499",
"items" : [
{
"product" : "productOne",
"quantity" : "2"
},
{
"product" : "productTwo",
"quantity" : "3"
}
]
}
I retrieve the data like this:
exports.productPurchased = functions.firestore
.document('purchases/{productPurchaseId}')
.onCreate((doc, context) => {
const documentId = context.params.productPurchaseId;
const purchaseData = doc.data();
const purchase = {
amount: `${purchaseData.amount}`,
uid: `${purchaseData.user_id}`,
phoneNumber: `${purchaseData.phone}`,
items: `${purchaseData.items}`, //this is where I have the issue
docId: documentId,
createdOn: admin.firestore.FieldValue.serverTimestamp()
}
return productPurchase(purchase)
})
The other fields are retrieved Ok, the challenge is with the array. I would like to get the array of objects and and insert them into the purchase object such that they become:
"productOne" : "2",
"productTwo" : "3"
Does anyone know how to do this?
CodePudding user response:
Remove the backticks to get the array
exports.productPurchased = functions.firestore
.document('purchases/{productPurchaseId}')
.onCreate((doc, context) => {
const documentId = context.params.productPurchaseId;
const purchaseData = doc.data();
const purchase = {
amount: `${purchaseData.amount}`,
uid: `${purchaseData.user_id}`,
phoneNumber: `${purchaseData.phone}`,
items: purchaseData.items, //this is where I have the issue
docId: documentId,
createdOn: admin.firestore.FieldValue.serverTimestamp()
}
return productPurchase(purchase)
})
and in your productPurchase function, receive the object:
const productPurchase = (data => {
const newData = data;
const pArray = Object.entries(data.items);
pArray.forEach(([key, val]) => {
newData[val.product] = val.quantity;
})
//do what you want with newData
})