49 lines
1.2 KiB
JavaScript
49 lines
1.2 KiB
JavaScript
import { apiService } from "./js/ApiService.js";
|
|
|
|
export class BasketModel {
|
|
constructor() {
|
|
this.items = [];
|
|
}
|
|
|
|
async loadBasketItems() {
|
|
this.items = await apiService.get('basket?_expand=product');
|
|
return this.items;
|
|
}
|
|
|
|
async addToBasket(productId, quantity = 1) {
|
|
const existingItem = this.items.find(item => item.productId === productId);
|
|
|
|
if (existingItem) {
|
|
return this.updateBasketItem(existingItem.id, {
|
|
quantity: existingItem.quantity + quantity
|
|
});
|
|
} else {
|
|
const newItem = await apiService.post('basket', {
|
|
productId,
|
|
quantity
|
|
});
|
|
this.items.push(newItem);
|
|
return newItem;
|
|
}
|
|
}
|
|
|
|
async updateBasketItem(itemId, data) {
|
|
const updatedItem = await apiService.put('basket', itemId, data);
|
|
this.items = this.items.map(item =>
|
|
item.id === itemId ? updatedItem : item
|
|
);
|
|
return updatedItem;
|
|
}
|
|
|
|
async removeFromBasket(itemId) {
|
|
await apiService.delete('basket', itemId);
|
|
this.items = this.items.filter(item => item.id !== itemId);
|
|
}
|
|
|
|
async clearBasket() {
|
|
await Promise.all(this.items.map(item =>
|
|
apiService.delete('basket', item.id)
|
|
));
|
|
this.items = [];
|
|
}
|
|
} |