Created
October 22, 2021 07:43
ecommerce-escalation v2
This file contains 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
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