Last active
May 9, 2022 18:37
-
-
Save zalun/de913017a01bf8754df705a0380609a5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// api/product/services/product.js | |
"use strict"; | |
const { createCoreService } = require("@strapi/strapi").factories; | |
module.exports = createCoreService("api::product.product", ({ strapi }) => ({ | |
async handleTransactionUpdate(event) { | |
const { result } = event; | |
strapi.log.info( | |
`Acting upon an updated transaction - id: ${result.id}, status: ${result.status}` | |
); | |
if (result.status === "COMPLETED") { | |
const productCollection = await strapi.query("api::product.product"); | |
// Collect all products mentioned in the transaction | |
const productIds = result.products.map((product) => product.id); | |
const productsList = await productCollection.findMany({ | |
id: { in_: productIds }, | |
}); | |
// Translate the list of products into a map with product uids as keys | |
const products = {}; | |
for (let i = 0; i < productsList.length; i++) { | |
products[productsList[i].id] = productsList[i]; | |
} | |
// Update the products inventory | |
const promises = []; | |
for (const idx in result.products) { | |
const boughtProduct = result.products[idx]; | |
const product = products[boughtProduct.id]; | |
promises.push( | |
productCollection.update({ | |
where: { id: product.id }, | |
data: { inventory: product.inventory - boughtProduct.quantity }, | |
}) | |
); | |
} | |
// Finish after all promises are resolved | |
await Promise.all(promises); | |
} | |
}, | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment