Skip to content

Commit d696b3c

Browse files
added error handling
1 parent 3ce26ea commit d696b3c

File tree

6 files changed

+79
-46
lines changed

6 files changed

+79
-46
lines changed

src/Umbraco.Commerce.Cart/Client/src/apis/ucc-add-to-cart-button.api.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ export class UccAddToCartButtonApi {
2727
]
2828

2929
private readonly _host: HTMLElement;
30-
private _productData:MasterProductData | null = null;
31-
private _cartRepository = new UccCartRepository();
3230
private _context = UCC_CART_CONTEXT;
31+
private _cartRepository:UccCartRepository;
32+
private _productData:MasterProductData | null = null;
3333

3434
constructor(host: HTMLElement) {
3535
this._host = host;
36+
this._cartRepository = new UccCartRepository(host);
3637
this._observeAttributes();
3738
this._bindEvents();
3839
}
@@ -42,7 +43,7 @@ export class UccAddToCartButtonApi {
4243
this._host.addEventListener('click', async (e) => {
4344
e.preventDefault();
4445
if (this._productData) {
45-
await this._cartRepository.addToCart(this._context.config.get()!.store!, this._productData).then(() => {
46+
this._cartRepository.addToCart(this._context.config.get()!.store!, this._productData).then(() => {
4647
this._host.dispatchEvent(new UccEvent(UccEvent.CART_CHANGED));
4748
this._host.dispatchEvent(new UccEvent(UccEvent.CART_OPEN));
4849
})
@@ -52,15 +53,21 @@ export class UccAddToCartButtonApi {
5253

5354
private _observeAttributes = () =>
5455
{
56+
const processAttributes = () => {
57+
this._productData = this._processDataAttributes(UccAddToCartButtonApi._attrMap, 'data-ucc-');
58+
}
59+
5560
const observer = new MutationObserver((mutations) => {
5661
mutations.forEach((mutation) => {
5762
if (mutation.type === 'attributes' && mutation.attributeName?.startsWith('data-ucc-')) {
58-
this._productData = this._processDataAttributes(UccAddToCartButtonApi._attrMap, 'data-ucc-');
63+
processAttributes();
5964
}
6065
});
6166
});
6267

6368
observer.observe(this._host, { attributes: true });
69+
70+
processAttributes();
6471
}
6572

6673
private _processDataAttributes = (attrMap:any, outerAttrKey: string | undefined = undefined) =>

src/Umbraco.Commerce.Cart/Client/src/apis/ucc.api.ts

Lines changed: 42 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
import { processAddToCartButtons } from "../processors/ucc-add-to-cart-button.processor.ts";
2-
import {Cart, CartConfig, CartOptions} from "../types.ts";
2+
import { Cart, CartConfig } from "../types.ts";
33
import { UCC_CART_CONTEXT } from "../contexts/ucc.context.ts";
44
import { UccCartModalElement } from "../components/ucc-cart-modal.element.ts";
55
import { UccEvent } from "../events/ucc.event.ts";
66
import { UccCartRepository } from "../repositories/cart.respository.ts";
7-
import {processCartButtons} from "../processors/ucc-cart-button.processor.ts";
8-
import {processCartCountLabels} from "../processors/ucc-cart-count-labels.processor.ts";
7+
import { processCartButtons } from "../processors/ucc-cart-button.processor.ts";
8+
import { processCartCountLabels } from "../processors/ucc-cart-count-labels.processor.ts";
99

1010
export class UccApi {
1111

1212
public readonly defaultLocales : Record<string, Record<string, string>> = {
1313
en: {
1414
cart_title: 'Cart Summary',
15-
close_cart: 'Close Cart',
15+
close_cart: 'Close Cart (ESC)',
1616
checkout: 'Checkout',
1717
taxes: 'Taxes',
1818
subtotal: 'Subtotal',
@@ -25,11 +25,12 @@ export class UccApi {
2525

2626
private readonly _host;
2727
private _context = UCC_CART_CONTEXT;
28-
private _cartRepository = new UccCartRepository();
28+
private _cartRepository: UccCartRepository;
2929
private _cartModal: UccCartModalElement;
3030

3131
constructor(host: HTMLElement) {
3232
this._host = host;
33+
this._cartRepository = new UccCartRepository(host);
3334
this._cartModal = new UccCartModalElement(host);
3435
this._observerDocumentLang();
3536
this._bindEvents();
@@ -51,6 +52,12 @@ export class UccApi {
5152
this._host.addEventListener(UccEvent.CART_CHANGED, async () => {
5253
await this._fetchCart();
5354
});
55+
this._host.addEventListener(UccEvent.CART_ERROR, async (e: Event) => {
56+
const evt = e as UccEvent;
57+
const config = this._context.config.get();
58+
config?.onError?.apply(this, [evt.Detail]);
59+
console.log(evt.Detail);
60+
});
5461
}
5562

5663
private _observerDocumentLang = () => {
@@ -64,33 +71,32 @@ export class UccApi {
6471
observer.observe(this._host.ownerDocument.documentElement, { attributes: true });
6572
}
6673

67-
public init = (config?:Partial<CartConfig>) => {
68-
69-
if (config)
70-
{
71-
const { locales, ...rest } = config;
72-
73-
// Merge config with default values
74-
const cfg : CartConfig = {
75-
lang: 'en',
76-
...rest
77-
}
74+
public init = async (config:Partial<CartConfig>) => {
7875

79-
cfg.locales = {
80-
...this.defaultLocales,
81-
...locales
82-
}
83-
84-
console.log(cfg)
76+
const { locales, ...rest } = config;
77+
78+
// Merge config with default values
79+
const cfg : CartConfig = {
80+
lang: 'en',
81+
...rest
82+
}
8583

86-
// Set the config in context
87-
this._context.config.set(cfg);
88-
89-
// Fetch the cart
90-
this._fetchCart();
84+
cfg.locales = {
85+
...this.defaultLocales,
86+
...locales
9187
}
9288

93-
// Process UI elements
89+
// Set the config in context
90+
this._context.config.set(cfg);
91+
92+
// Fetch the cart
93+
await this._fetchCart();
94+
95+
// Bind UI elements
96+
this.bind();
97+
}
98+
99+
public bind = () => {
94100
processAddToCartButtons(this._host);
95101
processCartButtons(this._host);
96102
processCartCountLabels(this._host);
@@ -134,6 +140,14 @@ export class UccApi {
134140
});
135141
}
136142

143+
public setOnError = (callback:(msg:string) => void) => {
144+
const currentConfig = this._context.config.get()!;
145+
this._context.config.set({
146+
...currentConfig,
147+
onError: callback
148+
});
149+
}
150+
137151
public openCart = () => {
138152
this._cartModal.open();
139153
}

src/Umbraco.Commerce.Cart/Client/src/components/ucc-cart-modal.element.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { UCC_CART_CONTEXT } from "../contexts/ucc.context.ts";
2-
import { Cart, CartConfig, CartItem } from "../types.ts";
2+
import { CartConfig, CartItem } from "../types.ts";
33
import { UccModalElement } from "./ucc-modal.element.ts";
44
import { debounce, delegate } from "../utils.ts";
55
import { UccCartRepository } from "../repositories/cart.respository.ts";
@@ -8,7 +8,7 @@ import { UccEvent } from "../events/ucc.event.ts";
88
export class UccCartModalElement extends UccModalElement
99
{
1010
private _context = UCC_CART_CONTEXT;
11-
private _cartRepository = new UccCartRepository();
11+
private _cartRepository: UccCartRepository;
1212

1313
private get storeIdOrAlias() {
1414
return this._context.config.get()!.store!;
@@ -20,6 +20,7 @@ export class UccCartModalElement extends UccModalElement
2020

2121
constructor(host: HTMLElement) {
2222
super(host);
23+
this._cartRepository = new UccCartRepository(host);
2324
this._attachCartTemplate();
2425
this._observerContext();
2526
}
@@ -60,10 +61,9 @@ export class UccCartModalElement extends UccModalElement
6061
private _renderCart()
6162
{
6263
const config = this._context.config.get();
63-
const cart = this._context.cart.get();
64+
if (!config) return;
6465

65-
if (!config || !cart) return;
66-
66+
const cart = this._context.cart.get();
6767
if (cart && cart.items.length > 0) {
6868
this._host.querySelector('.ucc-cart-items')!.innerHTML = cart.items.map((item) => {
6969
const propsToDisplay = Object.keys(item.properties ?? {}).filter((x) => (config.properties ?? []).map(y => y.toLowerCase()).includes(x.toLowerCase()));
@@ -179,7 +179,7 @@ export class UccCartModalElement extends UccModalElement
179179
<span class="ucc-cart-total-value ucc-split__right"></span>
180180
</div>
181181
</div>
182-
<div class="ucc-cart-message">Calculate shipping and apply discounts during checkout</div>
182+
<div class="ucc-cart-message"></div>
183183
<a class="ucc-cart-checkout" href="#"></a>
184184
`)
185185

src/Umbraco.Commerce.Cart/Client/src/events/ucc.event.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@ export class UccEvent extends Event {
33
public static CART_CHANGED = 'ucc-cart-changed';
44
public static CART_OPEN = 'ucc-cart-open';
55
public static CART_CLOSE = 'ucc-cart-close';
6+
public static CART_ERROR = 'ucc-cart-error';
67

7-
constructor(type:string) {
8+
public Detail?: any;
9+
10+
constructor(type:string, detail?:any) {
811
super(type, { bubbles: true, composed: true });
12+
this.Detail = detail;
913
}
1014
}

src/Umbraco.Commerce.Cart/Client/src/repositories/cart.respository.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
import { AddToCartRequest, UpdateCartItemRequest } from "../types.ts";
2+
import {UccEvent} from "../events/ucc.event.ts";
23

34
export class UccCartRepository {
45

6+
private _host: Element;
7+
8+
constructor(host: Element) {
9+
this._host = host;
10+
}
11+
12+
513
async getCart(storeIdOrAlias:string) {
614
return await this._doRequest(storeIdOrAlias, '/umbraco/commerce/cart/api/v1/session/cart', 'GET');
715
}
@@ -27,18 +35,17 @@ export class UccCartRepository {
2735
'Store': storeIdOrAlias
2836
},
2937
body: body ? JSON.stringify(body) : undefined
38+
}).then(async response => {
39+
return { ok: response.ok, data: await response.text() };
3040
}).then(response => {
3141
if (response.ok) {
32-
return response.text();
42+
return response.data ? JSON.parse(response.data) : undefined;
3343
} else {
34-
console.log("Oops! There was a problem submitting your form");
35-
}
36-
}).then(data => {
37-
if (data) {
38-
return JSON.parse(data);
44+
return Promise.reject(response.data);
3945
}
4046
}).catch(error => {
41-
console.log(error)
47+
this._host.dispatchEvent(new UccEvent(UccEvent.CART_ERROR, error));
48+
return Promise.reject(error);
4249
});
4350
}
4451

src/Umbraco.Commerce.Cart/Client/src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export type CartConfig = {
2323
properties?: string[]
2424
locales?: Record<string, Record<string, string>>
2525
showPricesIncludingTax?: boolean
26+
onError?: (msg: string) => void
2627
}
2728

2829
export type Cart = {

0 commit comments

Comments
 (0)