Skip to content

Instantly share code, notes, and snippets.

@zalun
Last active May 9, 2022 18:37
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 zalun/de913017a01bf8754df705a0380609a5 to your computer and use it in GitHub Desktop.
Save zalun/de913017a01bf8754df705a0380609a5 to your computer and use it in GitHub Desktop.
// 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