@qbcart/cosmos
Version:
Azure Cosmos DB access common across the QBCart node ecosystem.
129 lines (128 loc) • 4.09 kB
JavaScript
/***********************************************
* @license
* Copyright (c) QBCart Inc. All rights reserved.
************************************************/
export default class Cart {
parent;
constructor(parent) {
this.parent = parent;
}
async getItem(id, userId) {
try {
if (!id)
throw 'Missing an id.';
if (!userId)
throw 'Must be a valid userId';
return await this.parent.read(id, `CART-ITEM-${userId}`);
}
catch (error) {
console.log(error);
return null;
}
}
async getItems(returnProps, userId, lastSynced) {
try {
if (!userId)
throw 'Must be a valid userId';
const query = `SELECT ${returnProps} FROM c WHERE c._ts > ${lastSynced ?? 0}`;
return ((await this.parent.queryAll(query, `CART-ITEM-${userId}`)) ??
[]);
}
catch (error) {
console.log(error);
return [];
}
}
async addItem(id, price, quantity, sortOrder, userId) {
try {
if (!id)
throw 'Missing an id.';
if (!userId)
throw 'Must be a valid userId';
const item = await this.getItem(id, userId);
if (item) {
item.price = price;
item.quantity += quantity;
// Don't assign item.sortOrder = sortOrder, as this shuffle the previously added order
await this.parent.container
.item(item.id, item.Discriminator)
.replace(item);
}
else {
await this.parent.container.items.create({
id: id,
Discriminator: `CART-ITEM-${userId}`,
Created: new Date(),
price: price,
quantity: quantity,
sortOrder: sortOrder
});
}
return true;
}
catch (error) {
console.log(error);
return false;
}
}
async updateItem(id, price, quantity, userId) {
try {
if (!id)
throw 'Missing an id.';
if (!userId)
throw 'Must be a valid userId.';
const item = await this.getItem(id, userId);
if (!item)
throw 'Cannot update item that does not exist.';
item.price = price;
item.quantity = quantity;
await this.parent.container
.item(item.id, item.Discriminator)
.replace(item);
return true;
}
catch (error) {
console.log(error);
return false;
}
}
async removeItem(id, userId) {
try {
if (!id)
throw 'Missing an id.';
if (!userId)
throw 'Must be a valid userId.';
const item = await this.getItem(id, userId);
if (!item)
throw 'Cannot remove item that does not exist.';
item.quantity = 0;
await this.parent.container
.item(item.id, item.Discriminator)
.replace(item);
return true;
}
catch (error) {
console.log(error);
return false;
}
}
async clearItems(userId) {
try {
if (!userId)
throw 'Must be a valid userId.';
const items = await this.getItems('*', userId);
for (let i = 0; i < items.length; i++) {
items[i].quantity = 0;
items[i].Discriminator = `CART-ITEM-${userId}`;
await this.parent.container
.item(items[i].id, items[i].Discriminator)
.replace(items[i]);
}
return true;
}
catch (error) {
console.log(error);
return false;
}
}
}