My first question on this platform! I'm currently learning JavaScript and working on implementing APIs for a college project. I have the API body that passes a JSON object like this:
[
{
"id":1,
"issueDate":"2021/11/29 09:33",
"state": "DELIVERED",
"products": [{"SKUId":12,"description":"a product","price":10.99,"qty":30},
{"SKUId":180,"description":"another product","price":11.99,"qty":20},...],
"supplierId" : 1,
"transportNote":{"deliveryDate":"2021/12/29"},
"skuItems" : [{"SKUId":12,"rfid":"12345678901234567890123456789016"},{"SKUId":12,"rfid":"12345678901234567890123456789017"},...]
},
...
]
I am facing difficulties in parsing products into an array of product objects.
class Product {
constructor(SKUId,description,price, qty,) {
this.id = id;
this.price = price;
this.SKUId = SKUId;
this.qty = qty;
this.description = description;
};
}
module.exports = Product;
Here is the code snippet I am using for the parsing:
try {
if (Object.keys(req.body).length === 0) {
return res.status(422).json({ error: `Empty body request` }).end();
}
if (!validate_date(req.body.issueDate) ){
return res.status(422).json({ error:`Issue Date Not Valid ` }).end();
}
if (req.body.products === undefined)
return res.status(422).json({ error: `Products not defined in the call` }).end();
if (req.body.supplierId === undefined)
return res.status(422).json({ error: `SupplierId Not defined` }).end();
let lastID = await db.getLastIdFromTable('RestockOrder');
let trID = incrementID(lastID);
let order = new Restock_order(trID, req.body.issueDate, "ISSUED", req.body.supplierId, undefined);
await db.createRestockOrder(order);
//THE ISSUE OCCURS HERE
const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty));
order.addProducts(products);
products.forEach(async (x) => await db.addProductToSKURestockTable(x));
return res.status(200).end();
}
Following the line const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty));, an exception is thrown (handled within a try-catch block), and I'm unable to figure out the root cause of the parsing issue. Appreciate any help in resolving this problem. Thank you!