Skip to content

Instantly share code, notes, and snippets.

@simonrenoult
Created May 18, 2018 14:50
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 simonrenoult/3491e8e677cf5e9378cc95760d2800bd to your computer and use it in GitHub Desktop.
Save simonrenoult/3491e8e677cf5e9378cc95760d2800bd to your computer and use it in GitHub Desktop.
// API route to create an order
app.post("/orders", async (req, res) => {
// HTTP request payload validation
// abortEarly is false in order to retrieve all the errors at once
const { error } = Joi.validate(req.body, orderSchema, {
abortEarly: false
});
if (error) {
const errorMessage = error.details.map(({ message, context }) =>
Object.assign({ message, context })
);
return res.status(400).send({ data: errorMessage });
}
// Fetch the list of products based on the products provided in the order
const productList = await Product.findAll({
where: {
id: { [Op.in]: req.body.product_list.map(id => parseInt(id, 0)) }
}
});
if (productList.length === 0) {
return res.status(400).send({
data: [
{ message: "Unknown products", context: { key: "product_list" } }
]
});
}
const productListData = productList.map(product => product.toJSON());
// Compute the total weight order
const orderTotalWeight = productListData
.map(p => p.weight)
.reduce((prev, cur) => prev + cur, 0);
// Compute the total price amount
const orderProductListPrice = productListData
.map(p => p.price)
.reduce((prev, cur) => prev + cur, 0);
// Compute the shipment price amount
const SHIPMENT_PRICE_STEP = 25;
const SHIPMENT_WEIGHT_STEP = 10;
const orderShipmentPrice =
SHIPMENT_PRICE_STEP * Math.round(orderTotalWeight / SHIPMENT_WEIGHT_STEP);
// Compute the order price
let totalAmount = orderProductListPrice + orderShipmentPrice;
// Compute the discount
const DISCOUNT_THRESHOLD = 1000;
const DISCOUNT_RATIO = 0.95;
if (totalAmount > DISCOUNT_THRESHOLD) {
totalAmount = totalAmount * DISCOUNT_RATIO;
}
const orderData = Object.assign(
{
total_amount: totalAmount,
shipment_amount: orderShipmentPrice,
total_weight: orderTotalWeight
},
{ product_list: req.body.product_list }
);
const order = await Order.create(orderData);
res.set("Location", `/orders/${order.id}`);
res.status(201).send();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment