diff options
| author | ruki <waruqi@gmail.com> | 2018-11-08 00:38:48 +0800 |
|---|---|---|
| committer | ruki <waruqi@gmail.com> | 2018-11-07 21:53:09 +0800 |
| commit | 26105034da4fcce7ac883c899d781f016559310d (patch) | |
| tree | c459a5dc4e3aa0972d9919033ece511ce76dd129 /node_modules/algoliasearch/src/store.js | |
| parent | 2c77f00f1a7ecb6c8192f9c16d3b2001b254a107 (diff) | |
| download | xmake-docs-26105034da4fcce7ac883c899d781f016559310d.tar.gz xmake-docs-26105034da4fcce7ac883c899d781f016559310d.zip | |
switch to vuepress
Diffstat (limited to 'node_modules/algoliasearch/src/store.js')
| -rw-r--r-- | node_modules/algoliasearch/src/store.js | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/node_modules/algoliasearch/src/store.js b/node_modules/algoliasearch/src/store.js new file mode 100644 index 00000000..a84c9c05 --- /dev/null +++ b/node_modules/algoliasearch/src/store.js @@ -0,0 +1,86 @@ +var debug = require('debug')('algoliasearch:src/hostIndexState.js'); +var localStorageNamespace = 'algoliasearch-client-js'; + +var store; +var moduleStore = { + state: {}, + set: function(key, data) { + this.state[key] = data; + return this.state[key]; + }, + get: function(key) { + return this.state[key] || null; + } +}; + +var localStorageStore = { + set: function(key, data) { + moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure + + try { + var namespace = JSON.parse(global.localStorage[localStorageNamespace]); + namespace[key] = data; + global.localStorage[localStorageNamespace] = JSON.stringify(namespace); + return namespace[key]; + } catch (e) { + return localStorageFailure(key, e); + } + }, + get: function(key) { + try { + return JSON.parse(global.localStorage[localStorageNamespace])[key] || null; + } catch (e) { + return localStorageFailure(key, e); + } + } +}; + +function localStorageFailure(key, e) { + debug('localStorage failed with', e); + cleanup(); + store = moduleStore; + return store.get(key); +} + +store = supportsLocalStorage() ? localStorageStore : moduleStore; + +module.exports = { + get: getOrSet, + set: getOrSet, + supportsLocalStorage: supportsLocalStorage +}; + +function getOrSet(key, data) { + if (arguments.length === 1) { + return store.get(key); + } + + return store.set(key, data); +} + +function supportsLocalStorage() { + try { + if ('localStorage' in global && + global.localStorage !== null) { + if (!global.localStorage[localStorageNamespace]) { + // actual creation of the namespace + global.localStorage.setItem(localStorageNamespace, JSON.stringify({})); + } + return true; + } + + return false; + } catch (_) { + return false; + } +} + +// In case of any error on localStorage, we clean our own namespace, this should handle +// quota errors when a lot of keys + data are used +function cleanup() { + try { + global.localStorage.removeItem(localStorageNamespace); + } catch (_) { + // nothing to do + } +} |
