UNPKG

mobx-persist-store

Version:
55 lines (54 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StorageAdapter = void 0; const utils_1 = require("./utils"); class StorageAdapter { constructor(options) { this.options = options; } async setItem(key, item) { var _a; const { stringify = true, debugMode = false } = this.options; const __mps__ = (0, utils_1.omitObjectProperties)({ expireInTimestamp: this.options.expireIn ? (0, utils_1.buildExpireTimestamp)(this.options.expireIn) : undefined, version: this.options.version, }, (value) => value === undefined); const data = Object.keys(__mps__).length ? Object.assign({}, item, { __mps__, }) : item; const content = stringify ? JSON.stringify(data) : data; (0, utils_1.consoleDebug)(debugMode, `${key} - setItem:`, content); await ((_a = this.options.storage) === null || _a === void 0 ? void 0 : _a.setItem(key, content)); } async getItem(key) { var _a, _b, _c; const { removeOnExpiration = true, debugMode = false, version } = this.options; const storageData = await ((_a = this.options.storage) === null || _a === void 0 ? void 0 : _a.getItem(key)); let parsedData; try { parsedData = JSON.parse(storageData) || {}; } catch (error) { parsedData = storageData || {}; } const hasExpired = (0, utils_1.hasTimestampExpired)((_b = parsedData.__mps__) === null || _b === void 0 ? void 0 : _b.expireInTimestamp); const mismatchedVersion = version && ((_c = parsedData.__mps__) === null || _c === void 0 ? void 0 : _c.version) !== version; (0, utils_1.consoleDebug)(debugMode, `${key} - hasExpired`, hasExpired); (0, utils_1.consoleDebug)(debugMode, `${key} - mismatchedVersion`, mismatchedVersion); if ((hasExpired && removeOnExpiration) || mismatchedVersion) { await this.removeItem(key); } parsedData = hasExpired || mismatchedVersion ? {} : parsedData; (0, utils_1.consoleDebug)(debugMode, `${key} - (getItem):`, parsedData); return parsedData; } async removeItem(key) { var _a; const { debugMode = false } = this.options; (0, utils_1.consoleDebug)(debugMode, `${key} - (removeItem): storage was removed`); await ((_a = this.options.storage) === null || _a === void 0 ? void 0 : _a.removeItem(key)); } } exports.StorageAdapter = StorageAdapter;