@apicart/store-sdk
Version:
Apicart SDK for integrating store into any web application
109 lines (82 loc) • 2.69 kB
text/typescript
import Apicart from '@apicart/core-sdk';
import CartEventDispatcherEvents from '../EventDispatcherEvents/CartEventDispatcherEvents';
import PaymentMethod from '../Entity/Payment/PaymentMethod';
import ShippingMethod from '../Entity/Shipping/ShippingMethod';
class Storage
{
private readonly CART_STORAGE_KEY = 'store.cartHash';
private readonly CUSTOMER_STORAGE_KEY: string = 'store.customerHash';
private readonly PAYMENT_METHODS_STORAGE_KEY: string = 'store.paymentMethods';
private readonly SHIPPING_METHODS_STORAGE_KEY: string = 'store.shippingMethods';
constructor() {
Apicart.Utils.EventDispatcher.addListener(
'apicart-storage-cart-finish',
CartEventDispatcherEvents.FINISHED,
(): void => {
this.clearCartHash();
this.clearCustomerHash();
}
);
}
public saveCartHash(hash: string): void
{
Apicart.Storage.setItem(this.CART_STORAGE_KEY, hash);
}
public getCartHash(): string|null
{
return Apicart.Storage.getItem(this.CART_STORAGE_KEY);
}
public clearCartHash(): void
{
Apicart.Storage.removeItem(this.CART_STORAGE_KEY);
}
public saveCustomerHash(hash: string): void
{
Apicart.Storage.setItem(this.CUSTOMER_STORAGE_KEY, hash);
}
public getCustomerHash(): string | null
{
return Apicart.Storage.getItem(this.CUSTOMER_STORAGE_KEY);
}
public clearCustomerHash(): void
{
Apicart.Storage.removeItem(this.CUSTOMER_STORAGE_KEY);
}
public savePaymentMethods(paymentMethods: PaymentMethod[]): void
{
const serializedPaymentMethods = [];
Apicart.Utils.Loops.forEach(paymentMethods, (paymentMethod: PaymentMethod): void => {
serializedPaymentMethods.push(paymentMethod.serialize());
});
Apicart.Storage.setItem(this.PAYMENT_METHODS_STORAGE_KEY, serializedPaymentMethods);
}
public getPaymentMethods(): PaymentMethod[]
{
return Apicart.Storage.getItem(this.PAYMENT_METHODS_STORAGE_KEY);
}
public clearPaymentMethods(): void
{
Apicart.Storage.removeItem(this.PAYMENT_METHODS_STORAGE_KEY);
}
public saveShippingMethods(shippingMethods: ShippingMethod[]): void
{
const serializedShippingMethods = [];
Apicart.Utils.Loops.forEach(shippingMethods, (shippingMethod: ShippingMethod): void => {
serializedShippingMethods.push(shippingMethod.serialize());
});
Apicart.Storage.setItem(this.SHIPPING_METHODS_STORAGE_KEY, serializedShippingMethods);
}
public getShippingMethods(): ShippingMethod[]
{
return Apicart.Storage.getItem(this.SHIPPING_METHODS_STORAGE_KEY);
}
public clearShippingMethods(): void
{
Apicart.Storage.removeItem(this.SHIPPING_METHODS_STORAGE_KEY);
}
public clear(): void
{
Apicart.Storage.setItem('store', {});
}
}
export default new Storage();