From eea39e1627a79fb679cd842385f9733c5e3a1808 Mon Sep 17 00:00:00 2001 From: Leonardo Matos Date: Thu, 29 Aug 2019 15:02:04 -0300 Subject: [PATCH] feat(storage): try to preset cart data from storage --- src/index.js | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 0c106b7..6ec5bfc 100644 --- a/src/index.js +++ b/src/index.js @@ -7,7 +7,7 @@ import { _config } from '@ecomplus/utils' /** - * JS lib to handle products search with E-Com Plus stores. + * Vanilla JS library to handle shopping cart object on E-Com Plus stores. * @module @ecomplus/shopping-cart * @see EcomCart * @@ -28,10 +28,71 @@ const _key = 'ecomShoppingCart' const _storage = typeof window === 'object' && window.localStorage export default function (storeId, storageKey = _key, localStorage = _storage) { + const self = this + /** * Respective Store ID number. * @name EcomCart#storeId * @type {number} */ this.storeId = storeId || _config.get('store_id') + + /** + * Item key to handle persistent JSON {@link EcomCart#data} + * with [localStorage]{@link EcomSearch#localStorage}. + * @name EcomCart#storageKey + * @type {string|null} + */ + this.storageKey = storageKey + + /** + * [Storage interface]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage}. + * @name EcomCart#localStorage + * @type {object} + */ + this.localStorage = localStorage + + /** + * Shopping cart data object. + * @name EcomCart#data + * @type {array} + */ + this.data = {} + + if (localStorage && storageKey) { + // try to preset cart data from storage + const json = localStorage.getItem(storageKey) + if (typeof data === 'string') { + let data + try { + data = JSON.parse(json) + } catch (e) { + // ignore invalid JSON + } + if (data && Array.isArray(data.items)) { + self.data = data + } + } + } } + +/** + * Construct a new shopping cart instance object. + * @class EcomCart + * @param {number} [storeId=_config.get('store_id')] - Preset Store ID number + * @param {string|null} [storageKey='ecomShoppingCart'] - Item key to persist search history data + * @param {object} [localStorage=window.localStorage] - + * [Local Storage interface]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage} + * + * @example + +const cart = new EcomCart() + + * + * @example + +// Defining Store ID other than the configured on `ecomUtils._config` +const storeId = 2000 +const cart = new EcomCart(storeId) + + */