src/cacheServiceAdapters.js
import angular from 'angular'
export default cacheAdaptersConfig
cacheAdaptersConfig.$inject = ['httpEtagProvider']
function cacheAdaptersConfig (httpEtagProvider) {
httpEtagProvider
.defineCacheServiceAdapter('$cacheFactory', {
config: {
storesDeepCopies: false
},
methods: {
createCache: function createCache ($cacheFactory, cacheId, options) {
$cacheFactory(cacheId, options)
},
getCache: function getCache ($cacheFactory, cacheId) {
return $cacheFactory.get(cacheId)
},
setItem: function setItem (cache, itemKey, value) {
cache.put(itemKey, value)
},
getItem: function getItem (cache, itemKey) {
return cache.get(itemKey)
},
removeItem: function removeItem (cache, itemKey) {
cache.remove(itemKey)
},
removeAllItems: function removeAllItems (cache, itemKey) {
cache.removeAll()
}
}
})
.defineCacheServiceAdapter('localStorage', {
config: {
storesDeepCopies: true
},
methods: {
createCache: angular.noop,
getCache: function getCache (localStorage, cacheId) {
return cacheId
},
setItem: function setItem (cacheId, itemKey, value) {
try {
itemKey = cacheId + ':' + itemKey
localStorage.setItem(itemKey, JSON.stringify(value))
} catch (e) {
}
},
getItem: function getItem (cacheId, itemKey) {
itemKey = cacheId + ':' + itemKey
return JSON.parse(localStorage.getItem(itemKey))
},
removeItem: function removeItem (cacheId, itemKey) {
itemKey = cacheId + ':' + itemKey
localStorage.removeItem(itemKey)
},
removeAllItems: function removeAllItems (cacheId, itemKey) {
var keyPrefix = cacheId + ':'
angular.forEach(localStorage, function (value, key) {
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key)
}
})
}
}
})
.defineCacheServiceAdapter('sessionStorage', {
config: {
storesDeepCopies: true
},
methods: {
createCache: angular.noop,
getCache: function getCache (sessionStorage, cacheId) {
return cacheId
},
setItem: function setItem (cacheId, itemKey, value) {
try {
itemKey = cacheId + ':' + itemKey
sessionStorage.setItem(itemKey, JSON.stringify(value))
} catch (e) {
}
},
getItem: function getItem (cacheId, itemKey) {
itemKey = cacheId + ':' + itemKey
return JSON.parse(sessionStorage.getItem(itemKey))
},
removeItem: function removeItem (cacheId, itemKey) {
itemKey = cacheId + ':' + itemKey
sessionStorage.removeItem(itemKey)
},
removeAllItems: function removeAllItems (cacheId, itemKey) {
var keyPrefix = cacheId + ':'
angular.forEach(sessionStorage, function (value, key) {
if (key.indexOf(keyPrefix) === 0) {
sessionStorage.removeItem(key)
}
})
}
}
})
}