UNPKG

@spfxappdev/storage

Version:
292 lines 13.1 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import { isNullOrEmpty, isset, isFunction, toBoolean, getUrlParameter } from '@spfxappdev/utility'; import { Logger } from '@spfxappdev/logger'; var defaultStorageSettings = { UrlParameter: { RefreshAll: 'ResetCache', RefreshOnly: 'ResetOnly' }, DefaultTimeToLife: 60, KeyPrefix: 'SPFxAppDev_' }; var sessionStorageSettings = __assign({}, defaultStorageSettings); var localStorageSettings = __assign({}, defaultStorageSettings); var StorageBase = /** @class */ (function () { function StorageBase(storage, settings) { if (settings === void 0) { settings = defaultStorageSettings; } this.expiredCacheKeySuffix = '_expire'; this.cacheLogCategory = 'SPFxAppDevCaching'; this.cache = storage; this.Settings = settings; this.logger = new Logger(this.cacheLogCategory); } /** * Get's the Value associated with the specified CacheKey from the Local-/Session- Storage. * @param {string} cacheKey The specified Key for the Cache. * @param {Function|null} delegateFunction The delegate Function which if set is Called to refresh the Value in the Cache. * @param {number} timeToLife The Time 'til the Cache expires in Minutes. */ StorageBase.prototype.get = function (cacheKey, delegateFunction, timeToLife) { if (delegateFunction === void 0) { delegateFunction = null; } if (timeToLife === void 0) { timeToLife = this.Settings.DefaultTimeToLife; } if (isNullOrEmpty(cacheKey)) { this.warn('cacheKey is required and cannot be null or empty'); return null; } var originalCacheKey = cacheKey; cacheKey = this.Settings.KeyPrefix + cacheKey; if (!isset(timeToLife)) { this.info('timeToLife is not set. Use default time to life of ' + this.Settings.DefaultTimeToLife + ' minutes.'); timeToLife = this.Settings.DefaultTimeToLife; } var cache = this.cache; // Browser-Support-Check if (!isset(cache)) { if (isFunction(delegateFunction)) { this.warn('call delegate function because browser does not support this storage type'); var valueToCache = delegateFunction(); return valueToCache; } this.warn('The browser does not support this storage type and the delagte function is null'); return null; } var refreshCacheValue = this.getUrlParameter(this.Settings.UrlParameter.RefreshAll); var refreshSpecific = this.getUrlParameter(this.Settings.UrlParameter.RefreshOnly); var refreshCache = toBoolean(refreshCacheValue); var cacheWasRemoved = window.SPFxAppDevCachingWasRemoved || false; if (refreshCache && !isset(window.SPFxAppDevCachingWasRemoved)) { this.log('remove all caching values. Because URL-Parameter is set'); this.clear(); window.SPFxAppDevCachingWasRemoved = true; cacheWasRemoved = true; } if (!refreshCache && isset(refreshSpecific)) { var keyArray = refreshSpecific.toLowerCase().split(','); for (var index = 0; index < keyArray.length; index++) { if (keyArray[index] !== originalCacheKey.toLowerCase()) { continue; } refreshCache = true; cacheWasRemoved = true; this.log('remove cache with key ' + cacheKey + '. Because URL-Parameter is set'); break; } } // Do not clear again, because it was already done if (isset(window.SPFxAppDevCachingWasRemoved)) { refreshCache = false; } var expireKey = cacheKey + this.expiredCacheKeySuffix; var isExpired = refreshCache || this.cacheIsExpired(cache.getItem(expireKey)); if (isExpired) { this.remove(originalCacheKey); } var cacheValue = cacheWasRemoved ? null : cache.getItem(cacheKey); if (isset(cacheValue)) { this.log('return cached value with key ' + originalCacheKey); var cacheReturnValue = null; try { cacheReturnValue = JSON.parse(cacheValue); } catch (e) { this.log('Could not parse JSON-String with value: ' + cacheValue); /* tslint:disable:no-eval */ cacheReturnValue = eval('(' + cacheValue + ')'); } return cacheReturnValue; } if (isFunction(delegateFunction)) { this.log('call delegate function to get the data and set in cache, because data is expired for cache with key ' + originalCacheKey); var valueToCache = delegateFunction(); this.set(originalCacheKey, valueToCache, timeToLife); return valueToCache; } this.warn('cannot execute the delegate function, because it is not defined or not a function'); return null; }; /** * Set's the Value under the specified CacheKey in the Local-/Session- Storage. * @param {string} cacheKey The specified Key for the Cache. * @param {any} cacheValue The Value to be set in the Cache. * @param {number} timeToLife The Time 'til the Cache expires in Minutes. */ StorageBase.prototype.set = function (cacheKey, cacheValue, timeToLife) { if (timeToLife === void 0) { timeToLife = this.Settings.DefaultTimeToLife; } if (isNullOrEmpty(cacheKey)) { this.warn('cacheKey is required and cannot be null or empty'); return; } cacheKey = this.Settings.KeyPrefix + cacheKey; if (!isset(timeToLife)) { this.info('timeToLife is not set. Use default time to life of ' + this.Settings.DefaultTimeToLife + ' minutes.'); timeToLife = this.Settings.DefaultTimeToLife; } var cache = this.cache; // Browser-Support-Check if (!isset(cache)) { this.warn('The browser does not support this storage type and the delagte function is null'); return; } try { cacheValue = JSON.stringify(cacheValue); // Set the Value to cache cache.setItem(cacheKey, cacheValue); // Set the expired date var currentTime = new Date(); currentTime.setMinutes(currentTime.getMinutes() + timeToLife); var expireKey = cacheKey + this.expiredCacheKeySuffix; cache.setItem(expireKey, currentTime.getTime().toString()); } catch (e) { this.log('Could not set cache value for key: ' + cacheKey); } }; // /** // * @param {boolean} includeUserId // * @param {WebPartContext|ApplicationCustomizerContext} ctx // */ // public getWebSpecificCacheKey (includeUserId: boolean, ctx: WebPartContext|ApplicationCustomizerContext): string { // const loginName: string = ctx.pageContext.user.loginName.replace(/[^\w\s]/gi, '_'); // const userKey: string = includeUserId ? ('_user_' + loginName) : ''; // return ctx.pageContext.web.id.toString().replace(/[^\w\s]/gi, '') + userKey; // } /** * Removes item from Cache based on the Key. * @param {string} cacheKey The Key within the Cache. */ StorageBase.prototype.remove = function (cacheKey) { this.log('remove cache with key ' + cacheKey); cacheKey = this.Settings.KeyPrefix + cacheKey; var expiresCacheKey = cacheKey + this.expiredCacheKeySuffix; this.removeFromCache(cacheKey, expiresCacheKey); }; /** * Removes every Key from the Cache/ Clears the Cache */ StorageBase.prototype.clear = function () { var cache = this.cache; if (!isset(cache)) { return; } for (var i = cache.length - 1; i >= 0; i--) { var key = cache.key(i); if (key.toLowerCase().indexOf(this.Settings.KeyPrefix.toLowerCase()) !== 0) { continue; } key = key.replace(this.Settings.KeyPrefix, ''); this.remove(key); } }; /** * checks if an item exist in cache by cacheKey * IMPORTANT: this is the generell getItem-Methode of the cache store. You have to pass the prefix for the cacheKey * as well to return the values that you stored via the this.set()-Methode or use the this.get()-Methode instead * @param {string} cacheKey The Key to determine. * @returns {boolean} <c>true</c> if the Key exists within the Cache, else <c>false</c>. */ StorageBase.prototype.exists = function (cacheKey) { return isset(this.cache) && isset(this.cache.getItem(cacheKey)); }; /** * @returns {string[]} An Array of all CacheKeys. */ StorageBase.prototype.getStorageKeys = function () { var storageCache = this.cache; var keyArray = []; if (!isset(storageCache)) { return keyArray; } for (var keyName in storageCache) { if (typeof storageCache[keyName] === 'string' && keyName.indexOf(this.Settings.KeyPrefix) === 0 && keyName.indexOf(this.expiredCacheKeySuffix) < 0) { keyArray.push(keyName); } } return keyArray; }; StorageBase.prototype.cacheIsExpired = function (expiredDate) { if (!isset(expiredDate)) { return true; } var currentTime = new Date(); var expiresIn = parseInt(expiredDate, 10); var timeInCache = new Date(expiresIn); return currentTime > timeInCache; }; StorageBase.prototype.getUrlParameter = function (parameterName) { return getUrlParameter(parameterName); }; StorageBase.prototype.log = function (text) { this.logger.log(text); }; StorageBase.prototype.warn = function (text) { this.logger.warn(text); }; StorageBase.prototype.info = function (text) { this.logger.info(text); }; StorageBase.prototype.removeFromCache = function (cacheKey, cacheExpireKey) { if (!isset(this.cache)) { this.log('removeFromCache this.cache is not set'); return; } this.cache.removeItem(cacheKey); this.cache.removeItem(cacheExpireKey); }; return StorageBase; }()); export { StorageBase }; var SessionStorage = /** @class */ (function (_super) { __extends(SessionStorage, _super); /** * @param {IStorageSettings} customSettings Settings like a custom Key-Prefix or the Time to Live. */ function SessionStorage(customSettings) { if (customSettings === void 0) { customSettings = SessionStorage.DefaultSettings; } return _super.call(this, window.sessionStorage, customSettings) || this; } SessionStorage.DefaultSettings = sessionStorageSettings; return SessionStorage; }(StorageBase)); export { SessionStorage }; var LocalStorage = /** @class */ (function (_super) { __extends(LocalStorage, _super); /** * @param {IStorageSettings} customSettings Settings like a custom Key-Prefix or the Time to Live. */ function LocalStorage(customSettings) { if (customSettings === void 0) { customSettings = LocalStorage.DefaultSettings; } return _super.call(this, window.localStorage, customSettings) || this; } LocalStorage.DefaultSettings = localStorageSettings; return LocalStorage; }(StorageBase)); export { LocalStorage }; //# sourceMappingURL=Storage.js.map