Skip to content

Instantly share code, notes, and snippets.

@Pyrolistical
Created October 22, 2021 07:43
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 Pyrolistical/c1794faf39905de121320bb947f24967 to your computer and use it in GitHub Desktop.
Save Pyrolistical/c1794faf39905de121320bb947f24967 to your computer and use it in GitHub Desktop.
ecommerce-escalation v2
import _ from 'lodash';
export class InsufficientStock extends Error {
constructor(message) {
super(message);
this.name = 'InsufficientStock';
}
}
export default (repository) => {
return {
async checkout(lineItems, shippingAddress, paymentDetails) {
return repository.checkoutTransaction(async (session) => {
const productSkus = _.map(lineItems, 'productSku');
const inventory = await session.findInventoryByProuctSkus(productSkus);
const inventoryStockByProductSku = _(inventory)
.keyBy('productSku')
.mapValues('stock')
.value();
const inventoryStockUpdates = [];
for (const {productSku, quantity} of lineItems) {
const remainingStock = inventoryStockByProductSku[productSku];
if (remainingStock < quantity) {
throw new InsufficientStock({
productSku,
remainingStock,
requestedStock: quantity
});
}
inventoryStockUpdates.push({
productSku,
stock: remainingStock - quantity
});
}
await session.updateInventoryStock(inventoryStockUpdates);
const orderID = await session.createOrder({
lineItems,
shippingAddress,
paymentDetails
});
return orderID;
});
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment