Skip to content

Instantly share code, notes, and snippets.

@alfari16
Last active November 21, 2018 03:26
Show Gist options
  • Select an option

  • Save alfari16/51a8894831bd071a814dd8302c6b6f36 to your computer and use it in GitHub Desktop.

Select an option

Save alfari16/51a8894831bd071a814dd8302c6b6f36 to your computer and use it in GitHub Desktop.
const router = require('express').Router();
const { Product } = require('../models/')
router.post('order', (req, res) => {
try {
let outOfStock = {
bool: false,
data: []
}
let allProduct = await Product.findAll({
where: {
id: {
in: req.body.items.map(el => el.id)
}
},
attributes: ['id', 'stock']
})
allProduct = allProduct.map(el => {
if (el.stock < req.body.items.find(inner => inner.id === el.id).item) {
outOfStock.bool = true
outOfStock.data.push(el)
}
return {
id: el.id,
stock: el.stock
}
})
//validation
if (req.body.items.length > allProduct.length) {
const notFound = req.items.length.filter(el =>
allProduct.find(inner => inner.id === el.id)
)
const error = {
errorMsg: 'Product not found',
data: notFound
}
return res.json(error)
}
if (outOfStock.bool) {
return res.json({
errorMsg: 'Stuff out of Stock',
data: outOfStock.data
})
)
}
await Promise.all(
allProduct.map(el => {
return Product.update(
{
stock:
el.stock - req.body.items.find(inner => inner.id === el.id).item
},
{
where: {
id: el.id
},
transaction
}
)
})
)
res.json({isOk:true})
} catch(err) {
res.status(500).json({
isError: true,
err
})
}
})
module.exports = router
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment