first question i post here.
I'm learning js and trying to do some APIs for a college project.
I have the body of the API that passes a JSON object like that:
[
{
"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 have problems parsing products into an array of product object.
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;
And in the end this is the code i use 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);
//THIS IS THE LINE OF THE CODE THAT DOESNT WORK
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();
}
After the command const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty)); the code launchs an exception (caught in a try- catch block) and i dont know what is the real problem in the parsing.
Thanks to everyone who will help me to fix this
your class product is not valid and constructor should start from id parameter
const products = req.body.products.map((x) => new Product(x.id,x.SKUId,... and so on
class Product {
id: number;
price: number;
qty: number;
description: string;
SKUId:number;
constructor(id:number,SKUId:number,description:string,price:number, qty:number) {
this.id = id;
this.price = price;
this.SKUId = SKUId;
this.qty = qty;
this.description = description;
};
}
When you call to request.body you already are in the array, so no need to add the .products part
Related
i get flat list from server and i must create a tree that list .
this is my model :
export interface ClaimManagerList {
id: number;
title: string;
parentId: number;
isChilde: boolean;
childs: Childes[];
}
export interface Childes {
id: number;
title: string;
parentId: number;
isChilde: boolean;
}
and in this code i convert flat list to tree list -> childs add to this property childs :
return this.claimsManagerService.getAll(this.searchParam).pipe(
map(data => {
data['records'].forEach(element => {
let model = {} as ClaimManagerList;
if (element.parentId == null) {
model.id = element.id;
model.isChilde = element.isChilde;
model.parentId = element.parentId;
model.title = element.title;
data['records'].forEach(child => {
if (child.parentId == element.id) {
let childe = {} as Childes;
childe.id = child.id;
childe.isChilde = child.isChilde;
childe.parentId = child.parentId;
childe.title = child.title;
model.childs.push(childe)
}
})
this.claims.push(model)
}
})
return this.claims;
})
but it show me error in this line :
model.childs.push(childe)
Cannot read property 'push'
whats the problem ? how can i solve this problem ?
This happening as model.childs is not set to an empty array at the beginning. We can resolve this like:
if(!model.childs) model.childs = [] as Childes[];
model.childs.push(childe) // This line should work fine now.
I'm going to propose some changes to your code to order to improve this. I hope these changes will be useful for you.
return this.claimsManagerService.getAll(this.searchParam).pipe(
map((data: any) => {
data.records.forEach((element: any) => {
let model: ClaimManagerList = {};
if (element.parentId == null) {
model.id = element.id;
model.isChilde = element.isChilde;
model.parentId = element.parentId;
model.title = element.title;
model.childs = [];
data.records.forEach((child: any) => {
if (child.parentId == element.id) {
let childe = {} as Childes;
childe.id = child.id;
childe.isChilde = child.isChilde;
childe.parentId = child.parentId;
childe.title = child.title;
model.childs.push(childe)
}
})
this.claims.push(model)
}
})
return this.claims;
})
I have a problem with some class for cart , which I must use in my work.
Here is code of this class:
class Cart {
constructor() {
this.key = "IT_SPA_CART";
if (!this.exists()) {
this.setItSpaCart([]);
}
}
get() {
const cookies = document.cookie.split(";");
return cookies.find(cookie => cookie.startsWith(this.key));
}
exists() {
return this.get() !== undefined;
}
getItSpaCart() {
const cookieValue = this.get().slice(12);
const parsedValue = JSON.parse(cookieValue);
return parsedValue;
}
setItSpaCart(value) {
const stringifiedValue = JSON.stringify(value);
document.cookie = `${this.key}=${stringifiedValue}`;
}
add(item) {
const cartValue = this.getItSpaCart();
this.setItSpaCart([...cartValue, item]);
}
remove(item) {
const cartValue = this.getItSpaCart();
const itemInCart = cartValue.findIndex(val => val.name === item.name);
if (itemInCart !== -1) {
cartValue.splice(itemInCart, 1);
this.setItSpaCart(cartValue);
}
}
}
When I try to use this class, e.g. with method add(), like this:
let cart = new Cart();
cart.add([{ num: 1, cost: 2 }, { num: 3, cost: 4 }, { num: 5, cost: 6 }]);
this error occur:
Cannot read property 'slice' of undefined at Cart.getItSpaCart
Why this is happend?
Thanks for every hint.
I had the same problem ;-) Maybe You already know how to fix it, but if not, perhaps solution is changing code in this line: const cookies = document.cookie.split(";");. I changed ("; ) into ("; ").
I am building up an ecommerce web in which i have my order Model class like this
import { User } from './user.model';
export class Order {
constructor(){}
amount: Number = 0;
status: String = "";
date: String = '';
products: [any];
userId: String = '';
user : User;
}
And user model like this
export class User{
name: string = '';
email: string = '';
country: string = '';
city: string = '';
mobileNumber: string = '';
address: string = '';
postalCode : string = '';
nearBy : string = '';
_id : string = '';
}
And i have a cart.service.ts in which i am calculating an order total amount like this
// Total amount
public getTotalAmount(): Observable<number> {
return this.cartItems.pipe(map((product: CartItem[]) => {
return products.reduce((prev, curr: CartItem) => {
return prev + curr.product.price * curr.quantity;
}, 0);
}));
}
Now on my checkout.component.ts i am binding values to order Model class like this
isUserLoggedIn: boolean = false;
orderRawData: any;
order: Order;
placeOrder() {
this.cartService.getTotalAmount().subscribe(total=>{
if (total) {
console.log('amount : ',total);
this.order.amount = total;
this.orderRawData = JSON.parse(localStorage.getItem('cartItem'));
if (this.isUserLoggedIn) {
this.order.userId = this.user._id;
}else{
this.order.user = this.user;
}
this.orderRawData.forEach((item,index)=>{
this.order.products.push({
id : item.product._id,
quantity : item.quantity
})
})
this.order.date = new Date().toLocaleString();
this.order.status = 'Pending';
console.log(this.order);
}
})
}
But it's giving me an error like this
What am i doing wrong?
You have declared order:
order: Order;
Bu it never gets assigned an object, so is undefined when you try to updated one of its properties.
this.order.amount = total;
// <--- undefined here
You somehow need to assign order, for example:
this.orderService.getOrder().subscribe(order => {
this.order = order;
});
Before you can consider updating properties on it.
Your order follows the 'Order' format but it's not initialize.
You can do like this:
1) order: Order = {
amount: 0,
status: null,
....
}
or 2) Update the Order class like:
export class Order {
amount: Number;
status: String;
...
constructor(_amount: Number = 0, _status: String = '', ...) {
this.amount = _amount;
this.status = _status;
....
}
}
In the component:
order: Order = new Order();
I am trying to display(log) the items that I added using the addItems() function when I call(log) the getItems() function..
console.log(cart.addItem("ITEMMSSS", 100, 10)) << puts out
ShoppingCart { itemName: 'ITEMMSSS', quantity: 100, price: 10 }
as expected
but the console.log(cart.getItems()) puts out -1-
when I console.log(this.addedItems) it logs out -undefined-(twice)
I don't understand why I don't have access to the returned value from the
addItem() function.
class ShoppingCart {
constructor(itemName, quantity, price) {
this.itemName = itemName
this.quantity = quantity
this.price = price
}
addItem(...items) {
const addedItems = new ShoppingCart(...items)
return addedItems
}
getItems(addedItems) {
const el = []
const selected = this.addedItems
const newArr = el.push(selected)
return newArr
}
clear(...item) {
// return items.slice(0, ...items).concat(items.slice(...items + 1))
}
clone(...items) {
// console.log(this)
// copiedCart.map((item) => {
// return item
// })
}
}
FIXed the issue,
class ShoppingCart {
constructor(items) {
this.items = []
}
addItem(name, quantity, pricePerUnit) {
const shopCart = this.items.push({
name: name,
quantity: quantity,
pricePerUnit: pricePerUnit
})
return shopCart
}
getItems(...items) {
const displayItems = this.items
return displayItems
}
clear(...items) {
const emptyCart = this.items.length = []
return emptyCart
}
clone(...items) {
const copyCart = new ShoppingCart()
copyCart.items = JSON.parse(JSON.stringify(this.items))
return copyCart
}
}
//
// const cart1 = new ShoppingCart('banana', 12, 23)
// const cart2 = cart1.clone()
// //
// console.log(cart2)
// //
module.exports = ShoppingCart;
But can't seem to get an immutable copy of the shoppingCart <--
fixed issue after reading about deep copying
clone(...items) {
const copyCart = new ShoppingCart()
copyCart.items = JSON.parse(JSON.stringify(this.items))
return copyCart
}
Couple ideas for author to think about:
1) addItem should be a function of an existing instance of ShopppingCart. Creating a new object inside addItems should not be necessary. I only know of returning a value from a setter to be usually only done for "fluent" setters practices so that you can chain them together. But that would be returning the current object.
2) getItems should usually not perform any logic. Usually getters return the current state of a variable / object member.
To address authors direct question:
You are returning the addItems object from the function but not storing it.
Try:
cart = cart.addItem("ITEMMSSS", 100, 10)
Controller returns Java.lang.stackoverflow error when calling from ajax.
My Ajax function is like this.
$.ajax({
url: '${pageContext.servletContext.contextPath}/exam/test',
type: 'POST',
data: 'examName='+examName,
success: function(response) {
alert(response);
}
});
Controller
#RequestMapping(value = "/exam/test", method = RequestMethod.POST)
public #ResponseBody List<SchoolExam> examsTest(#ModelAttribute(value = "examName") String examName, BindingResult result, WebRequest webRequest, ModelMap map, Principal principal) {
User loggedUser = userService.getUserByUserName(principal.getName());
***********************
Some code here
***********************
List<SchoolExam> schoolExams = new ArrayList<SchoolExam>();
for (School school : schools) {
if (student) {
Set<Student> students = school.getStudents();
for(Student std : students) {
if (std != null && !std.isEmpty()) {
schoolExams.add(new SchoolExam(std, true));
}
}
}
if (teacher) {
Set<Teacher> teachers = school.getEvents();
for (Teacher tchr : teachers) {
if (loggedUser.equals(tchr.getOwner())) {
schoolExams.add(new SchoolExam(tchr, true));
}
}
}
if (exam) {
Set<Exam> exams = school.getCampaigns();
for (Exam exam1 : exams) {
if (loggedUser.equals(exam1.getOwner())) {
schoolExams.add(new SchoolExam(exam1, true));
}
}
}
}
return schoolExams;
}
SchoolExam
public SchoolExam(Object obj, boolean editable) {
this.editable = editable;
if (obj instanceof Student) {
Student student = (Student) obj;
this.id = student.getId();
this.name = student.getName();
this.type = Constants.Student;
this.obj = student; // <-- This is causing issue here
}
if (obj instanceof Teacher) {
Teacher teacher = (Teacher) obj;
this.id = teacher.getId();
this.name = teacher.getName();
this.type = Constants.Teacher;
this.obj = teacher; // <-- This is causing issue here
}
if (obj instanceof Exam) {
Exam exam = (Exam) obj;
this.id = exam.getId();
this.name = exam.getName();
this.type = Constants.Exam;
this.obj = exam; // <-- This is causing issue here
}
}
Issue:
This is working fine when a form is submit then I can use all data by running foreach loop in jsp but when I tried to return list in my function then ajax work successfully and it also return me response
response in ajax
[
{
"id":"2123244",
"name":"UK School",
"type":"exam",
"editable":true,
"obj":
{
"id":"2123244",
"authorizationRequired":false,
"owner":
{
"id":"5676764554",
"company":
{
"id":"55435435345",
"name":"SchoolTest Software",
"enabled":true,
"size":3,
"sector":null,
"phone":"1231231232",
"schoolFees":5000,
"location":"US",
"users":
[
{
"id":"5676764554",
"company": // <-- Start Repeating here
{
"id":"55435435345",
"name":"SchoolTest Software",
"enabled":true,
"size":3,
"sector":null,
"phone":"1231231232",
"schoolFees":5000,
"location":"US",
"users":
[
{
"id":"5676764554",
"company": // <-- Repeating again
{
"id":"55435435345",
"name":"SchoolTest Software",
"enabled":true,
"size":3,
"sector":null,
"phone":"1231231232",
"schoolFees":5000,
"location":"US",
"users":
[
{
"id":"5676764554",
"company":// <-- It keeps repeating it self
but when I tried to print list value in controller it's only printing one value.
e.g:
for (SchoolExam schoolExam : schoolExams) {
System.out.println("Name: " + schoolExam.getName());
System.out.println("ID: " + schoolExam.getId());
Exam exam = (Exam) schoolExam.getObj();
System.out.println("Exam Name: " + exam.getName());
}
Output:
Name: UK School
ID: 2123244
Exam Name: UK School
Note:
If I comment obj line then everything works fine for me.
e.g:
this.obj = student;
this.obj = teacher;
this.obj = exam;
But I need to use this to get data as It contain data for different table.
Please find this file for error log that I'm getting in console.
So, What I'm doing wrong which cause this issue or I need to use any other way to prevent this issue.
Any suggestion or link will be helpful.
According to your error log file, you have a cyclic recursion in your Java classes. So Jackson try to serialize some objects infinitely.
The main problem is here : com.school.model.Company_$$_javassist_8["users"]->org.hibernate.collection.PersistentSet[0]->com.school.model.User["company"]->com.school.model.Company_$$_javassist_8["users"]
You have a property users containing a set of User containing a property ompany containr a Company containing the same users. So infinity loop.