Compare commits
1 Commits
master
...
revert-117
Author | SHA1 | Date |
---|---|---|
Gregory Pike | b5daef145b | 10 years ago |
@ -1,8 +0,0 @@
|
||||
<a name="0.1.1"></a>
|
||||
# 0.1.1 (2014-10-06)
|
||||
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
- update your `index.html` file to reference angular-local-storage at its new
|
||||
path inside the `dist` directory `/angular-local-storage/dist/angular-local-storage.js`
|
@ -0,0 +1 @@
|
||||
(function(){"use strict";var a=angular.module("LocalStorageModule",[]);a.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){this.prefix=a},this.setStorageType=function(a){this.storageType=a},this.setStorageCookie=function(a,b){this.cookie={expiry:a,path:b}},this.setStorageCookieDomain=function(a){this.cookie.domain=a},this.setNotify=function(a,b){this.notify={setItem:a,removeItem:b}},this.$get=["$rootScope","$window","$document",function(a,b,c){var d,e=this.prefix,f=this.cookie,g=this.notify,h=this.storageType;c||(c=document),"."!==e.substr(-1)&&(e=e?e+".":"");var i=function(a){return e+a},j=function(){try{var c=h in b&&null!==b[h],e=i("__"+Math.round(1e7*Math.random()));return c&&(d=b[h],d.setItem(e,""),d.removeItem(e)),c}catch(f){return h="cookie",a.$broadcast("LocalStorageModule.notification.error",f.message),!1}}(),k=function(b,c){if(!j)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),g.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:"cookie"}),q(b,c);"undefined"==typeof c&&(c=null);try{(angular.isObject(c)||angular.isArray(c))&&(c=angular.toJson(c)),d&&d.setItem(i(b),c),g.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:this.storageType})}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.message),q(b,c)}return!0},l=function(b){if(!j)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r(b);var c=d?d.getItem(i(b)):null;return c&&"null"!==c?"{"===c.charAt(0)||"["===c.charAt(0)?angular.fromJson(c):c:null},m=function(b){if(!j)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),g.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),s(b);try{d.removeItem(i(b)),g.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:this.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),s(b)}return!0},n=function(){if(!j)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=e.length,c=[];for(var f in d)if(f.substr(0,b)===e)try{c.push(f.substr(b))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.Description),[]}return c},o=function(b){b=b||"";var c=e.slice(0,-1),f=new RegExp(c+"."+b);if(!j)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),t();var g=e.length;for(var h in d)if(f.test(h))try{m(h.substr(g))}catch(i){return a.$broadcast("LocalStorageModule.notification.error",i.message),t()}return!0},p=function(){try{return navigator.cookieEnabled||"cookie"in c&&(c.cookie.length>0||(c.cookie="test").indexOf.call(c.cookie,"test")>-1)}catch(b){return a.$broadcast("LocalStorageModule.notification.error",b.message),!1}},q=function(b,d){if("undefined"==typeof d)return!1;if(!p())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var e="",g=new Date,h="";if(null===d?(g.setTime(g.getTime()+-864e5),e="; expires="+g.toGMTString(),d=""):0!==f.expiry&&(g.setTime(g.getTime()+24*f.expiry*60*60*1e3),e="; expires="+g.toGMTString()),b){var j="; path="+f.path;f.domain&&(h="; domain="+f.domain),c.cookie=i(b)+"="+encodeURIComponent(d)+e+j+h}}catch(k){return a.$broadcast("LocalStorageModule.notification.error",k.message),!1}return!0},r=function(b){if(!p())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var d=c.cookie&&c.cookie.split(";")||[],f=0;f<d.length;f++){for(var g=d[f];" "===g.charAt(0);)g=g.substring(1,g.length);if(0===g.indexOf(i(b)+"="))return decodeURIComponent(g.substring(e.length+b.length+1,g.length))}return null},s=function(a){q(a,null)},t=function(){for(var a=null,b=e.length,d=c.cookie.split(";"),f=0;f<d.length;f++){for(a=d[f];" "===a.charAt(0);)a=a.substring(1,a.length);var g=a.substring(b,a.indexOf("="));s(g)}},u=function(){return h},v=function(a,b,c){var d=l(b);null===d&&angular.isDefined(c)?d=c:angular.isObject(d)&&angular.isObject(c)&&(d=angular.extend(c,d)),a[b]=d,a.$watchCollection(b,function(a){k(b,a)})};return{isSupported:j,getStorageType:u,set:k,add:k,get:l,keys:n,remove:m,clearAll:o,bind:v,deriveKey:i,cookie:{set:q,add:q,get:r,remove:s,clearAll:t}}}]})}).call(this);
|
@ -1,456 +0,0 @@
|
||||
/**
|
||||
* An Angular module that gives you access to the browsers local storage
|
||||
* @version v0.1.5 - 2015-01-22
|
||||
* @link https://github.com/grevory/angular-local-storage
|
||||
* @author grevory <greg@gregpike.ca>
|
||||
* @license MIT License, http://www.opensource.org/licenses/MIT
|
||||
*/
|
||||
(function ( window, angular, undefined ) {
|
||||
/*jshint globalstrict:true*/
|
||||
'use strict';
|
||||
|
||||
var isDefined = angular.isDefined,
|
||||
isUndefined = angular.isUndefined,
|
||||
isNumber = angular.isNumber,
|
||||
isObject = angular.isObject,
|
||||
isArray = angular.isArray,
|
||||
extend = angular.extend,
|
||||
toJson = angular.toJson,
|
||||
fromJson = angular.fromJson;
|
||||
|
||||
|
||||
// Test if string is only contains numbers
|
||||
// e.g '1' => true, "'1'" => true
|
||||
function isStringNumber(num) {
|
||||
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
|
||||
}
|
||||
|
||||
var angularLocalStorage = angular.module('LocalStorageModule', []);
|
||||
|
||||
angularLocalStorage.provider('localStorageService', function() {
|
||||
|
||||
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
|
||||
// e.g. localStorageServiceProvider.setPrefix('yourAppName');
|
||||
// With provider you can use config as this:
|
||||
// myApp.config(function (localStorageServiceProvider) {
|
||||
// localStorageServiceProvider.prefix = 'yourAppName';
|
||||
// });
|
||||
this.prefix = 'ls';
|
||||
|
||||
// You could change web storage type localstorage or sessionStorage
|
||||
this.storageType = 'localStorage';
|
||||
|
||||
// Cookie options (usually in case of fallback)
|
||||
// expiry = Number of days before cookies expire // 0 = Does not expire
|
||||
// path = The web path the cookie represents
|
||||
this.cookie = {
|
||||
expiry: 30,
|
||||
path: '/'
|
||||
};
|
||||
|
||||
// Send signals for each of the following actions?
|
||||
this.notify = {
|
||||
setItem: true,
|
||||
removeItem: false
|
||||
};
|
||||
|
||||
// Setter for the prefix
|
||||
this.setPrefix = function(prefix) {
|
||||
this.prefix = prefix;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Setter for the storageType
|
||||
this.setStorageType = function(storageType) {
|
||||
this.storageType = storageType;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Setter for cookie config
|
||||
this.setStorageCookie = function(exp, path) {
|
||||
this.cookie = {
|
||||
expiry: exp,
|
||||
path: path
|
||||
};
|
||||
return this;
|
||||
};
|
||||
|
||||
// Setter for cookie domain
|
||||
this.setStorageCookieDomain = function(domain) {
|
||||
this.cookie.domain = domain;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Setter for notification config
|
||||
// itemSet & itemRemove should be booleans
|
||||
this.setNotify = function(itemSet, itemRemove) {
|
||||
this.notify = {
|
||||
setItem: itemSet,
|
||||
removeItem: itemRemove
|
||||
};
|
||||
return this;
|
||||
};
|
||||
|
||||
this.$get = ['$rootScope', '$window', '$document', '$parse', function($rootScope, $window, $document, $parse) {
|
||||
var self = this;
|
||||
var prefix = self.prefix;
|
||||
var cookie = self.cookie;
|
||||
var notify = self.notify;
|
||||
var storageType = self.storageType;
|
||||
var webStorage;
|
||||
|
||||
// When Angular's $document is not available
|
||||
if (!$document) {
|
||||
$document = document;
|
||||
} else if ($document[0]) {
|
||||
$document = $document[0];
|
||||
}
|
||||
|
||||
// If there is a prefix set in the config lets use that with an appended period for readability
|
||||
if (prefix.substr(-1) !== '.') {
|
||||
prefix = !!prefix ? prefix + '.' : '';
|
||||
}
|
||||
var deriveQualifiedKey = function(key) {
|
||||
return prefix + key;
|
||||
};
|
||||
// Checks the browser to see if local storage is supported
|
||||
var browserSupportsLocalStorage = (function () {
|
||||
try {
|
||||
var supported = (storageType in $window && $window[storageType] !== null);
|
||||
|
||||
// When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
|
||||
// is available, but trying to call .setItem throws an exception.
|
||||
//
|
||||
// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
|
||||
// that exceeded the quota."
|
||||
var key = deriveQualifiedKey('__' + Math.round(Math.random() * 1e7));
|
||||
if (supported) {
|
||||
webStorage = $window[storageType];
|
||||
webStorage.setItem(key, '');
|
||||
webStorage.removeItem(key);
|
||||
}
|
||||
|
||||
return supported;
|
||||
} catch (e) {
|
||||
storageType = 'cookie';
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
|
||||
return false;
|
||||
}
|
||||
}());
|
||||
|
||||
|
||||
|
||||
// Directly adds a value to local storage
|
||||
// If local storage is not available in the browser use cookies
|
||||
// Example use: localStorageService.add('library','angular');
|
||||
var addToLocalStorage = function (key, value) {
|
||||
// Let's convert undefined values to null to get the value consistent
|
||||
if (isUndefined(value)) {
|
||||
value = null;
|
||||
} else if (isObject(value) || isArray(value) || isNumber(+value || value)) {
|
||||
value = toJson(value);
|
||||
}
|
||||
|
||||
// If this browser does not support local storage use cookies
|
||||
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
|
||||
if (!browserSupportsLocalStorage) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
|
||||
}
|
||||
|
||||
if (notify.setItem) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
|
||||
}
|
||||
return addToCookies(key, value);
|
||||
}
|
||||
|
||||
try {
|
||||
if (isObject(value) || isArray(value)) {
|
||||
value = toJson(value);
|
||||
}
|
||||
if (webStorage) {webStorage.setItem(deriveQualifiedKey(key), value)};
|
||||
if (notify.setItem) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
|
||||
}
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
|
||||
return addToCookies(key, value);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Directly get a value from local storage
|
||||
// Example use: localStorageService.get('library'); // returns 'angular'
|
||||
var getFromLocalStorage = function (key) {
|
||||
|
||||
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
|
||||
if (!browserSupportsLocalStorage) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
|
||||
}
|
||||
|
||||
return getFromCookies(key);
|
||||
}
|
||||
|
||||
var item = webStorage ? webStorage.getItem(deriveQualifiedKey(key)) : null;
|
||||
// angular.toJson will convert null to 'null', so a proper conversion is needed
|
||||
// FIXME not a perfect solution, since a valid 'null' string can't be stored
|
||||
if (!item || item === 'null') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) {
|
||||
return fromJson(item);
|
||||
}
|
||||
|
||||
return item;
|
||||
};
|
||||
|
||||
// Remove an item from local storage
|
||||
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
|
||||
var removeFromLocalStorage = function (key) {
|
||||
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
|
||||
if (!browserSupportsLocalStorage) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
|
||||
}
|
||||
|
||||
if (notify.removeItem) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
|
||||
}
|
||||
return removeFromCookies(key);
|
||||
}
|
||||
|
||||
try {
|
||||
webStorage.removeItem(deriveQualifiedKey(key));
|
||||
if (notify.removeItem) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: self.storageType});
|
||||
}
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
|
||||
return removeFromCookies(key);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Return array of keys for local storage
|
||||
// Example use: var keys = localStorageService.keys()
|
||||
var getKeysForLocalStorage = function () {
|
||||
|
||||
if (!browserSupportsLocalStorage) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
|
||||
return false;
|
||||
}
|
||||
|
||||
var prefixLength = prefix.length;
|
||||
var keys = [];
|
||||
for (var key in webStorage) {
|
||||
// Only return keys that are for this app
|
||||
if (key.substr(0,prefixLength) === prefix) {
|
||||
try {
|
||||
keys.push(key.substr(prefixLength));
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
};
|
||||
|
||||
// Remove all data for this app from local storage
|
||||
// Also optionally takes a regular expression string and removes the matching key-value pairs
|
||||
// Example use: localStorageService.clearAll();
|
||||
// Should be used mostly for development purposes
|
||||
var clearAllFromLocalStorage = function (regularExpression) {
|
||||
|
||||
regularExpression = regularExpression || "";
|
||||
//accounting for the '.' in the prefix when creating a regex
|
||||
var tempPrefix = prefix.slice(0, -1);
|
||||
var testRegex = new RegExp(tempPrefix + '.' + regularExpression);
|
||||
|
||||
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
|
||||
if (!browserSupportsLocalStorage) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
|
||||
}
|
||||
|
||||
return clearAllFromCookies();
|
||||
}
|
||||
|
||||
var prefixLength = prefix.length;
|
||||
|
||||
for (var key in webStorage) {
|
||||
// Only remove items that are for this app and match the regular expression
|
||||
if (testRegex.test(key)) {
|
||||
try {
|
||||
removeFromLocalStorage(key.substr(prefixLength));
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
|
||||
return clearAllFromCookies();
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Checks the browser to see if cookies are supported
|
||||
var browserSupportsCookies = (function() {
|
||||
try {
|
||||
return $window.navigator.cookieEnabled ||
|
||||
("cookie" in $document && ($document.cookie.length > 0 ||
|
||||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
|
||||
return false;
|
||||
}
|
||||
}());
|
||||
|
||||
// Directly adds a value to cookies
|
||||
// Typically used as a fallback is local storage is not available in the browser
|
||||
// Example use: localStorageService.cookie.add('library','angular');
|
||||
var addToCookies = function (key, value) {
|
||||
|
||||
if (isUndefined(value)) {
|
||||
return false;
|
||||
} else if(isArray(value) || isObject(value)) {
|
||||
value = toJson(value);
|
||||
}
|
||||
|
||||
if (!browserSupportsCookies) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
var expiry = '',
|
||||
expiryDate = new Date(),
|
||||
cookieDomain = '';
|
||||
|
||||
if (value === null) {
|
||||
// Mark that the cookie has expired one day ago
|
||||
expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
|
||||
expiry = "; expires=" + expiryDate.toGMTString();
|
||||
value = '';
|
||||
} else if (cookie.expiry !== 0) {
|
||||
expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
|
||||
expiry = "; expires=" + expiryDate.toGMTString();
|
||||
}
|
||||
if (!!key) {
|
||||
var cookiePath = "; path=" + cookie.path;
|
||||
if(cookie.domain){
|
||||
cookieDomain = "; domain=" + cookie.domain;
|
||||
}
|
||||
$document.cookie = deriveQualifiedKey(key) + "=" + encodeURIComponent(value) + expiry + cookiePath + cookieDomain;
|
||||
}
|
||||
} catch (e) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Directly get a value from a cookie
|
||||
// Example use: localStorageService.cookie.get('library'); // returns 'angular'
|
||||
var getFromCookies = function (key) {
|
||||
if (!browserSupportsCookies) {
|
||||
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
|
||||
return false;
|
||||
}
|
||||
|
||||
var cookies = $document.cookie && $document.cookie.split(';') || [];
|
||||
for(var i=0; i < cookies.length; i++) {
|
||||
var thisCookie = cookies[i];
|
||||
while (thisCookie.charAt(0) === ' ') {
|
||||
thisCookie = thisCookie.substring(1,thisCookie.length);
|
||||
}
|
||||
if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
|
||||
var storedValues = decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length))
|
||||
try{
|
||||
var obj = JSON.parse(storedValues);
|
||||
return fromJson(obj)
|
||||
}catch(e){
|
||||
return storedValues
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
var removeFromCookies = function (key) {
|
||||
addToCookies(key,null);
|
||||
};
|
||||
|
||||
var clearAllFromCookies = function () {
|
||||
var thisCookie = null, thisKey = null;
|
||||
var prefixLength = prefix.length;
|
||||
var cookies = $document.cookie.split(';');
|
||||
for(var i = 0; i < cookies.length; i++) {
|
||||
thisCookie = cookies[i];
|
||||
|
||||
while (thisCookie.charAt(0) === ' ') {
|
||||
thisCookie = thisCookie.substring(1, thisCookie.length);
|
||||
}
|
||||
|
||||
var key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
|
||||
removeFromCookies(key);
|
||||
}
|
||||
};
|
||||
|
||||
var getStorageType = function() {
|
||||
return storageType;
|
||||
};
|
||||
|
||||
// Add a listener on scope variable to save its changes to local storage
|
||||
// Return a function which when called cancels binding
|
||||
var bindToScope = function(scope, key, def, lsKey) {
|
||||
lsKey = lsKey || key;
|
||||
var value = getFromLocalStorage(lsKey);
|
||||
|
||||
if (value === null && isDefined(def)) {
|
||||
value = def;
|
||||
} else if (isObject(value) && isObject(def)) {
|
||||
value = extend(def, value);
|
||||
}
|
||||
|
||||
$parse(key).assign(scope, value);
|
||||
|
||||
return scope.$watch(key, function(newVal) {
|
||||
addToLocalStorage(lsKey, newVal);
|
||||
}, isObject(scope[key]));
|
||||
};
|
||||
|
||||
// Return localStorageService.length
|
||||
// ignore keys that not owned
|
||||
var lengthOfLocalStorage = function() {
|
||||
var count = 0;
|
||||
var storage = $window[storageType];
|
||||
for(var i = 0; i < storage.length; i++) {
|
||||
if(storage.key(i).indexOf(prefix) === 0 ) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
return {
|
||||
isSupported: browserSupportsLocalStorage,
|
||||
getStorageType: getStorageType,
|
||||
set: addToLocalStorage,
|
||||
put: addToLocalStorage,
|
||||
add: addToLocalStorage, //DEPRECATED
|
||||
get: getFromLocalStorage,
|
||||
keys: getKeysForLocalStorage,
|
||||
remove: removeFromLocalStorage,
|
||||
clearAll: clearAllFromLocalStorage,
|
||||
bind: bindToScope,
|
||||
deriveKey: deriveQualifiedKey,
|
||||
length: lengthOfLocalStorage,
|
||||
cookie: {
|
||||
isSupported: browserSupportsCookies,
|
||||
set: addToCookies,
|
||||
add: addToCookies, //DEPRECATED
|
||||
get: getFromCookies,
|
||||
remove: removeFromCookies,
|
||||
clearAll: clearAllFromCookies
|
||||
}
|
||||
};
|
||||
}];
|
||||
});
|
||||
})( window, window.angular );
|
@ -1,7 +0,0 @@
|
||||
/**
|
||||
* An Angular module that gives you access to the browsers local storage
|
||||
* @version v0.1.5 - 2015-01-22
|
||||
* @link https://github.com/grevory/angular-local-storage
|
||||
* @author grevory <greg@gregpike.ca>
|
||||
* @license MIT License, http://www.opensource.org/licenses/MIT
|
||||
*/!function(a,b){"use strict";function c(a){return/^-?\d+\.?\d*$/.test(a.replace(/["']/g,""))}var d=b.isDefined,e=b.isUndefined,f=b.isNumber,g=b.isObject,h=b.isArray,i=b.extend,j=b.toJson,k=b.fromJson,l=b.module("LocalStorageModule",[]);l.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){return this.prefix=a,this},this.setStorageType=function(a){return this.storageType=a,this},this.setStorageCookie=function(a,b){return this.cookie={expiry:a,path:b},this},this.setStorageCookieDomain=function(a){return this.cookie.domain=a,this},this.setNotify=function(a,b){return this.notify={setItem:a,removeItem:b},this},this.$get=["$rootScope","$window","$document","$parse",function(a,b,l,m){var n,o=this,p=o.prefix,q=o.cookie,r=o.notify,s=o.storageType;l?l[0]&&(l=l[0]):l=document,"."!==p.substr(-1)&&(p=p?p+".":"");var t=function(a){return p+a},u=function(){try{var c=s in b&&null!==b[s],d=t("__"+Math.round(1e7*Math.random()));return c&&(n=b[s],n.setItem(d,""),n.removeItem(d)),c}catch(e){return s="cookie",a.$broadcast("LocalStorageModule.notification.error",e.message),!1}}(),v=function(b,c){if(e(c)?c=null:(g(c)||h(c)||f(+c||c))&&(c=j(c)),!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:"cookie"}),B(b,c);try{(g(c)||h(c))&&(c=j(c)),n&&n.setItem(t(b),c),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:o.storageType})}catch(d){return a.$broadcast("LocalStorageModule.notification.error",d.message),B(b,c)}return!0},w=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),C(b);var d=n?n.getItem(t(b)):null;return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)||c(d)?k(d):d:null},x=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),D(b);try{n.removeItem(t(b)),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:o.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),D(b)}return!0},y=function(){if(!u)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=p.length,c=[];for(var d in n)if(d.substr(0,b)===p)try{c.push(d.substr(b))}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.Description),[]}return c},z=function(b){b=b||"";var c=p.slice(0,-1),d=new RegExp(c+"."+b);if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),E();var e=p.length;for(var f in n)if(d.test(f))try{x(f.substr(e))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),E()}return!0},A=function(){try{return b.navigator.cookieEnabled||"cookie"in l&&(l.cookie.length>0||(l.cookie="test").indexOf.call(l.cookie,"test")>-1)}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),!1}}(),B=function(b,c){if(e(c))return!1;if((h(c)||g(c))&&(c=j(c)),!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var d="",f=new Date,i="";if(null===c?(f.setTime(f.getTime()+-864e5),d="; expires="+f.toGMTString(),c=""):0!==q.expiry&&(f.setTime(f.getTime()+24*q.expiry*60*60*1e3),d="; expires="+f.toGMTString()),b){var k="; path="+q.path;q.domain&&(i="; domain="+q.domain),l.cookie=t(b)+"="+encodeURIComponent(c)+d+k+i}}catch(m){return a.$broadcast("LocalStorageModule.notification.error",m.message),!1}return!0},C=function(b){if(!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var c=l.cookie&&l.cookie.split(";")||[],d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t(b)+"=")){var f=decodeURIComponent(e.substring(p.length+b.length+1,e.length));try{var g=JSON.parse(f);return k(g)}catch(h){return f}}}return null},D=function(a){B(a,null)},E=function(){for(var a=null,b=p.length,c=l.cookie.split(";"),d=0;d<c.length;d++){for(a=c[d];" "===a.charAt(0);)a=a.substring(1,a.length);var e=a.substring(b,a.indexOf("="));D(e)}},F=function(){return s},G=function(a,b,c,e){e=e||b;var f=w(e);return null===f&&d(c)?f=c:g(f)&&g(c)&&(f=i(c,f)),m(b).assign(a,f),a.$watch(b,function(a){v(e,a)},g(a[b]))},H=function(){for(var a=0,c=b[s],d=0;d<c.length;d++)0===c.key(d).indexOf(p)&&a++;return a};return{isSupported:u,getStorageType:F,set:v,put:v,add:v,get:w,keys:y,remove:x,clearAll:z,bind:G,deriveKey:t,length:H,cookie:{isSupported:A,set:B,add:B,get:C,remove:D,clearAll:E}}}]})}(window,window.angular);
|
@ -1,18 +0,0 @@
|
||||
/*jshint globalstrict:true*/
|
||||
'use strict';
|
||||
|
||||
var isDefined = angular.isDefined,
|
||||
isUndefined = angular.isUndefined,
|
||||
isNumber = angular.isNumber,
|
||||
isObject = angular.isObject,
|
||||
isArray = angular.isArray,
|
||||
extend = angular.extend,
|
||||
toJson = angular.toJson,
|
||||
fromJson = angular.fromJson;
|
||||
|
||||
|
||||
// Test if string is only contains numbers
|
||||
// e.g '1' => true, "'1'" => true
|
||||
function isStringNumber(num) {
|
||||
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
'use strict';
|
||||
//Mock localStorage
|
||||
function localStorageMock() {
|
||||
var storage = {};
|
||||
Object.defineProperties(storage, {
|
||||
setItem: {
|
||||
value: function(key, value) {
|
||||
storage[key] = value || '';
|
||||
},
|
||||
enumerable: false,
|
||||
writable: true
|
||||
},
|
||||
getItem: {
|
||||
value: function(key) {
|
||||
return storage[key];
|
||||
},
|
||||
enumerable: false,
|
||||
writable: true
|
||||
},
|
||||
removeItem: {
|
||||
value: function(key) {
|
||||
delete storage[key];
|
||||
},
|
||||
enumerable: false,
|
||||
writable: true
|
||||
},
|
||||
length: {
|
||||
get: function() {
|
||||
return Object.keys(storage).length;
|
||||
},
|
||||
enumerable: false
|
||||
},
|
||||
key: {
|
||||
value: function(i) {
|
||||
var aKeys = Object.keys(storage);
|
||||
return aKeys[i] || null;
|
||||
},
|
||||
enumerable: false
|
||||
}
|
||||
});
|
||||
return storage;
|
||||
}
|
@ -1,565 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
describe('localStorageService', function() {
|
||||
var elmSpy;
|
||||
|
||||
//Actions
|
||||
function getItem(key) {
|
||||
return function($window, localStorageService) {
|
||||
elmSpy = spyOn($window.localStorage, 'getItem').andCallThrough();
|
||||
localStorageService.get(key);
|
||||
};
|
||||
}
|
||||
|
||||
function addItem(key, value) {
|
||||
return function($window, localStorageService) {
|
||||
elmSpy = spyOn($window.localStorage, 'setItem').andCallThrough();
|
||||
localStorageService.set(key, value);
|
||||
};
|
||||
}
|
||||
|
||||
function addItemWithPut(key, value) {
|
||||
return function($window, localStorageService) {
|
||||
elmSpy = spyOn($window.localStorage, 'setItem').andCallThrough();
|
||||
localStorageService.put(key, value);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function removeItem(key) {
|
||||
return function($window, localStorageService) {
|
||||
elmSpy = spyOn($window.localStorage, 'removeItem').andCallThrough();
|
||||
localStorageService.remove(key);
|
||||
};
|
||||
}
|
||||
|
||||
//Expectations
|
||||
function expectGetting(key) {
|
||||
return function() {
|
||||
expect(elmSpy).toHaveBeenCalledWith(key);
|
||||
};
|
||||
}
|
||||
|
||||
function expectAdding(key, value) {
|
||||
return function() {
|
||||
expect(elmSpy).toHaveBeenCalledWith(key, value);
|
||||
};
|
||||
}
|
||||
|
||||
function expectRemoving(key) {
|
||||
return function() {
|
||||
expect(elmSpy).toHaveBeenCalledWith(key);
|
||||
};
|
||||
}
|
||||
|
||||
function expectMatching(key, expected) {
|
||||
return function(localStorageService) {
|
||||
expect(localStorageService.get(key)).toEqual(expected);
|
||||
};
|
||||
}
|
||||
|
||||
function expectStorageTyping(type) {
|
||||
return function(localStorageService) {
|
||||
expect(localStorageService.getStorageType()).toEqual(type);
|
||||
};
|
||||
}
|
||||
|
||||
function expectSupporting(expected) {
|
||||
return function(localStorageService) {
|
||||
expect(localStorageService.isSupported).toEqual(expected);
|
||||
};
|
||||
}
|
||||
|
||||
function expectCookieSupporting(expected) {
|
||||
return function(localStorageService) {
|
||||
expect(localStorageService.cookie.isSupported).toEqual(expected);
|
||||
};
|
||||
}
|
||||
|
||||
function expectDomain(domain) {
|
||||
return function($document, localStorageService) {
|
||||
localStorageService.set('foo','bar'); //Should trigger first time
|
||||
expect($document.cookie.indexOf('domain=' + domain)).not.toEqual(-1);
|
||||
};
|
||||
}
|
||||
|
||||
function expectCookieConfig(exp, path) {
|
||||
return function($document, localStorageService) {
|
||||
localStorageService.set('foo','bar'); //Should trigger first time
|
||||
// Just compare the expiry date, not the time, because of daylight savings
|
||||
var expiryStringPartial = exp.substr(0, exp.indexOf(new Date().getFullYear()));
|
||||
expect($document.cookie.indexOf('expires=' + expiryStringPartial)).not.toEqual(-1);
|
||||
expect($document.cookie.indexOf('path=' + path)).not.toEqual(-1);
|
||||
};
|
||||
}
|
||||
|
||||
//Provider
|
||||
function setPrefix(prefix) {
|
||||
return function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider.setPrefix(prefix);
|
||||
};
|
||||
}
|
||||
|
||||
function setNotify(itemSet, itemRemove) {
|
||||
return function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider.setNotify(itemSet, itemRemove);
|
||||
};
|
||||
}
|
||||
|
||||
function setStorage(type) {
|
||||
return function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider.setStorageType(type);
|
||||
};
|
||||
}
|
||||
|
||||
function setCookieDomain(domain) {
|
||||
return function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider.setStorageCookieDomain(domain);
|
||||
};
|
||||
}
|
||||
|
||||
function setStorageCookie(exp, path) {
|
||||
return function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider.setStorageCookie(exp, path);
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(module('LocalStorageModule', function($provide) {
|
||||
|
||||
$provide.value('$window', {
|
||||
localStorage: localStorageMock()
|
||||
});
|
||||
|
||||
}));
|
||||
|
||||
it('isSupported should be true', inject(
|
||||
expectSupporting(true)
|
||||
));
|
||||
|
||||
it('typing should be "localStorage" by default, if supported', inject(
|
||||
expectStorageTyping('localStorage')
|
||||
));
|
||||
|
||||
it('should add key to localeStorage with initial prefix(ls)', inject(
|
||||
addItem('foo', 'bar'),
|
||||
expectAdding('ls.foo', 'bar')
|
||||
));
|
||||
|
||||
it('should add key to localeStorage null if value not provided', inject(
|
||||
addItem('foo'),
|
||||
expectAdding('ls.foo', null)
|
||||
));
|
||||
|
||||
it('should add key to localStorage using put method', inject(
|
||||
addItemWithPut('key', 777),
|
||||
expectAdding('ls.key', angular.toJson(777)),
|
||||
expectMatching('key', 777)
|
||||
));
|
||||
|
||||
it('should support to set custom prefix', function() {
|
||||
module(setPrefix('myApp'));
|
||||
inject(
|
||||
addItem('foo', 'bar'),
|
||||
expectAdding('myApp.foo', 'bar')
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to chain functions in the config phase', function() {
|
||||
module(function(localStorageServiceProvider) {
|
||||
localStorageServiceProvider
|
||||
.setPrefix('chain')
|
||||
.setNotify(false, true)
|
||||
.setStorageType('session');
|
||||
});
|
||||
inject(function(localStorageService) {
|
||||
expect(localStorageService.deriveKey('foo')).toEqual('chain.foo');
|
||||
expect(localStorageService.getStorageType()).toEqual('session');
|
||||
});
|
||||
});
|
||||
|
||||
it('should be able to return the derive key', function() {
|
||||
module(setPrefix('myApp'));
|
||||
inject(function(localStorageService) {
|
||||
expect(localStorageService.deriveKey('foo')).toEqual('myApp.foo');
|
||||
});
|
||||
});
|
||||
|
||||
it('should be able to set and get arrays', function() {
|
||||
var values = ['foo', 'bar', 'baz'];
|
||||
inject(
|
||||
addItem('key', values),
|
||||
expectAdding('ls.key', angular.toJson(values)),
|
||||
expectMatching('key', values)
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to set and get objects', function() {
|
||||
var values = { 0: 'foo', 1: 'bar', 2: 'baz' };
|
||||
inject(
|
||||
addItem('key', values),
|
||||
expectAdding('ls.key', angular.toJson(values)),
|
||||
expectMatching('key', values)
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to set and get integers', function() {
|
||||
inject(
|
||||
addItem('key', 777),
|
||||
expectAdding('ls.key', angular.toJson(777)),
|
||||
expectMatching('key', 777)
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to set and get float numbers', function() {
|
||||
inject(
|
||||
addItem('key', 123.123),
|
||||
expectAdding('ls.key', angular.toJson(123.123)),
|
||||
expectMatching('key', 123.123)
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to set and get strings', function() {
|
||||
inject(
|
||||
addItem('key', 'string'),
|
||||
expectAdding('ls.key', 'string'),
|
||||
expectMatching('key', 'string')
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to set and get numbers as a strings', function() {
|
||||
inject(
|
||||
addItem('key', '777'),
|
||||
expectAdding('ls.key', angular.toJson('777')),
|
||||
expectMatching('key', '777')
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to get items', inject(
|
||||
getItem('key'),
|
||||
expectGetting('ls.key')
|
||||
));
|
||||
|
||||
it('should be able to remove items', inject(
|
||||
removeItem('lorem.ipsum'),
|
||||
expectRemoving('ls.lorem.ipsum')
|
||||
));
|
||||
|
||||
it('should be able only to remove owned keys', inject(function($window, localStorageService) {
|
||||
localStorageService.set('appKey', 'appValue');
|
||||
$window.localStorage.setItem('appKey', 'appValue');
|
||||
|
||||
expect($window.localStorage.getItem('ls.appKey')).toBeDefined();
|
||||
expect($window.localStorage.getItem('appKey')).toBeDefined();
|
||||
|
||||
localStorageService.remove('appKey');
|
||||
|
||||
expect($window.localStorage.getItem('ls.appKey')).not.toBeDefined();
|
||||
expect($window.localStorage.getItem('appKey')).toBeDefined();
|
||||
}));
|
||||
|
||||
it('should broadcast event on settingItem', inject(function($rootScope, localStorageService) {
|
||||
var setSpy = spyOn($rootScope, '$broadcast');
|
||||
localStorageService.set('Ariel', 'Mashraki');
|
||||
expect(setSpy).toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should not broadcast event on removingItem', inject(function($rootScope, localStorageService) {
|
||||
var removeSpy = spyOn($rootScope, '$broadcast');
|
||||
localStorageService.remove('Ariel', 'Mashraki');
|
||||
expect(removeSpy).not.toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should be able to change notify/broadcasting settings', function() {
|
||||
module(setNotify(false, false));
|
||||
inject(function($rootScope, localStorageService) {
|
||||
var spy = spyOn($rootScope, '$broadcast');
|
||||
localStorageService.set('a8m', 'foobar');
|
||||
localStorageService.remove('a8m', 'foobar');
|
||||
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should be able to notify/broadcasting if set', function() {
|
||||
module(setNotify(true, true));
|
||||
inject(function($rootScope, localStorageService) {
|
||||
var spy = spyOn($rootScope, '$broadcast');
|
||||
|
||||
localStorageService.set('a8m', 'foobar');
|
||||
localStorageService.remove('a8m', 'foobar');
|
||||
expect(spy.callCount).toEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('should be able to bind to scope', inject(function($rootScope, localStorageService) {
|
||||
|
||||
localStorageService.set('property', 'oldValue');
|
||||
localStorageService.bind($rootScope, 'property');
|
||||
|
||||
$rootScope.property = 'newValue';
|
||||
$rootScope.$digest();
|
||||
|
||||
expect($rootScope.property).toEqual(localStorageService.get('property'));
|
||||
}));
|
||||
|
||||
it('should be able to unbind from scope variable', inject(function($rootScope, localStorageService) {
|
||||
|
||||
localStorageService.set('property', 'oldValue');
|
||||
var lsUnbind = localStorageService.bind($rootScope, 'property');
|
||||
|
||||
$rootScope.property = 'newValue';
|
||||
$rootScope.$digest();
|
||||
|
||||
expect($rootScope.property).toEqual(localStorageService.get('property'));
|
||||
|
||||
lsUnbind();
|
||||
$rootScope.property = 'anotherValue';
|
||||
$rootScope.$digest();
|
||||
|
||||
expect($rootScope.property).not.toEqual(localStorageService.get('property'));
|
||||
}));
|
||||
|
||||
it('should be able to bind to properties of objects', inject(function($rootScope, localStorageService) {
|
||||
|
||||
localStorageService.set('obj.property', 'oldValue');
|
||||
localStorageService.bind($rootScope, 'obj.property');
|
||||
|
||||
expect($rootScope.obj.property).toEqual(localStorageService.get('obj.property'));
|
||||
|
||||
$rootScope.obj.property = 'newValue';
|
||||
$rootScope.$digest();
|
||||
|
||||
expect($rootScope.obj.property).toEqual(localStorageService.get('obj.property'));
|
||||
}));
|
||||
|
||||
it('should be able to bind to scope using different key', inject(function($rootScope, localStorageService) {
|
||||
|
||||
localStorageService.set('lsProperty', 'oldValue');
|
||||
localStorageService.bind($rootScope, 'property', undefined, 'lsProperty');
|
||||
|
||||
expect($rootScope.property).toEqual(localStorageService.get('lsProperty'));
|
||||
|
||||
$rootScope.property = 'newValue';
|
||||
$rootScope.$digest();
|
||||
|
||||
expect($rootScope.property).toEqual(localStorageService.get('lsProperty'));
|
||||
}));
|
||||
|
||||
it('should $watch with deep comparison only for objects', inject(function($rootScope, localStorageService) {
|
||||
var mocks = [{}, [], 'string', 90, false];
|
||||
var expectation = [true, true, false, false, false];
|
||||
var results = [];
|
||||
|
||||
spyOn($rootScope, '$watch').andCallFake(function(key, func, eq) {
|
||||
results.push(eq);
|
||||
});
|
||||
|
||||
mocks.forEach(function(elm, i) {
|
||||
localStorageService.set('mock' + i, elm);
|
||||
localStorageService.bind($rootScope, 'mock' + i);
|
||||
});
|
||||
|
||||
expect(results).toEqual(expectation);
|
||||
}));
|
||||
|
||||
it('should be able to return it\'s owned keys amount', inject(
|
||||
function(localStorageService, $window) {
|
||||
|
||||
for(var i = 0; i < 10; i++) {
|
||||
localStorageService.set('key' + i, 'val' + i);
|
||||
$window.localStorage.setItem('key' + i, 'val' + i);
|
||||
}
|
||||
expect(localStorageService.length()).toEqual(10);
|
||||
expect($window.localStorage.length).toEqual(20);
|
||||
}));
|
||||
|
||||
it('should be able to clear all owned keys from storage',inject(function($window, localStorageService) {
|
||||
for(var i = 0; i < 10; i++) {
|
||||
localStorageService.set('key' + i, 'val' + i);
|
||||
$window.localStorage.setItem('key' + i, 'val' + i);
|
||||
}
|
||||
|
||||
localStorageService.clearAll();
|
||||
//remove only owned keys
|
||||
for(var l = 0; l < 10; l++) {
|
||||
expect(localStorageService.get('key' + l)).toEqual(null);
|
||||
expect($window.localStorage.getItem('key' + l)).toEqual('val' + l);
|
||||
}
|
||||
}));
|
||||
|
||||
it('should return array of all owned keys', inject(function($window, localStorageService) {
|
||||
//set keys
|
||||
for(var i = 0; i < 10; i++) {
|
||||
//localStorageService
|
||||
localStorageService.set('ownKey' + i, 'val' + i);
|
||||
//window.localStorage
|
||||
$window.localStorage.setItem('windowKey' + i, 'val' + i);
|
||||
}
|
||||
localStorageService.keys().forEach(function(el, i) {
|
||||
expect(el).toEqual('ownKey' + i);
|
||||
});
|
||||
}));
|
||||
|
||||
//sessionStorage
|
||||
describe('SessionStorage', function() {
|
||||
|
||||
beforeEach(module('LocalStorageModule', function($provide) {
|
||||
$provide.value('$window', {
|
||||
sessionStorage: localStorageMock()
|
||||
});
|
||||
}));
|
||||
|
||||
it('should be able to change storage to SessionStorage', function() {
|
||||
module(setStorage('sessionStorage'));
|
||||
|
||||
inject(function($window, localStorageService) {
|
||||
var setSpy = spyOn($window.sessionStorage, 'setItem'),
|
||||
getSpy = spyOn($window.sessionStorage, 'getItem'),
|
||||
removeSpy = spyOn($window.sessionStorage, 'removeItem');
|
||||
|
||||
localStorageService.set('foo', 'bar');
|
||||
localStorageService.get('foo');
|
||||
localStorageService.remove('foo');
|
||||
|
||||
expect(setSpy).toHaveBeenCalledWith('ls.foo', 'bar');
|
||||
expect(getSpy).toHaveBeenCalledWith('ls.foo');
|
||||
expect(removeSpy).toHaveBeenCalledWith('ls.foo');
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
it('type should be sessionStorage', function() {
|
||||
module(setStorage('sessionStorage'));
|
||||
inject(
|
||||
expectStorageTyping('sessionStorage')
|
||||
);
|
||||
});
|
||||
|
||||
it('isSupported should be true on sessionStorage mode', function() {
|
||||
module(setStorage('sessionStorage'));
|
||||
inject(
|
||||
expectSupporting(true)
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
//cookie
|
||||
describe('Cookie', function() {
|
||||
|
||||
beforeEach(module('LocalStorageModule', function($provide) {
|
||||
$provide.value('$window', {
|
||||
localStorage: false,
|
||||
sessionStorage: false,
|
||||
navigator: {
|
||||
cookieEnabled: true
|
||||
}
|
||||
});
|
||||
$provide.value('$document', {
|
||||
cookie: ''
|
||||
});
|
||||
}));
|
||||
|
||||
it('isSupported should be false on fallback mode', inject(
|
||||
expectSupporting(false)
|
||||
));
|
||||
|
||||
it('cookie.isSupported should be true if cookies are enabled', inject(
|
||||
expectCookieSupporting(true)
|
||||
));
|
||||
|
||||
it('fallback storage type should be cookie', inject(
|
||||
expectStorageTyping('cookie')
|
||||
));
|
||||
|
||||
it('should be able to add to cookie domain', function() {
|
||||
module(setCookieDomain('.example.org'));
|
||||
inject(expectDomain('.example.org'));
|
||||
});
|
||||
|
||||
it('should be able to config expiry and path', function() {
|
||||
module(setStorageCookie(60, '/path'));
|
||||
inject(expectCookieConfig(new Date().addDays(60), '/path'));
|
||||
});
|
||||
|
||||
it('should be able to set and get cookie', inject(function(localStorageService) {
|
||||
localStorageService.set('cookieKey', 'cookieValue');
|
||||
expect(localStorageService.get('cookieKey')).toEqual('cookieValue');
|
||||
}));
|
||||
|
||||
it('should be able to remove from cookie', inject(function(localStorageService) {
|
||||
localStorageService.set('cookieKey', 'cookieValue');
|
||||
localStorageService.remove('cookieKey');
|
||||
expect(localStorageService.get('cookieKey')).toEqual('');
|
||||
}));
|
||||
|
||||
it('should be able to set and get objects from cookie', inject(function(localStorageService) {
|
||||
//use as a fallback
|
||||
localStorageService.set('cookieKey', { a: { b: 1 } });
|
||||
expect(localStorageService.get('cookieKey')).toEqual({ a: { b: 1 } });
|
||||
//use directly
|
||||
localStorageService.cookie.set('cookieKey', { a: 2 });
|
||||
expect(localStorageService.cookie.get('cookieKey')).toEqual({ a: 2 });
|
||||
}));
|
||||
|
||||
it('should be able to set and get arrays from cookie', inject(function(localStorageService) {
|
||||
//use as a fallback
|
||||
localStorageService.set('cookieKey', [1, 2, 3, [ 1, 2, 3 ]]);
|
||||
expect(localStorageService.get('cookieKey')).toEqual([1, 2, 3, [ 1, 2, 3 ]]);
|
||||
//use directly
|
||||
localStorageService.cookie.set('cookieKey', ['foo', 'bar']);
|
||||
expect(localStorageService.cookie.get('cookieKey')).toEqual(['foo', 'bar']);
|
||||
}));
|
||||
|
||||
it('should be able to clear all owned keys from cookie', inject(function(localStorageService, $document) {
|
||||
localStorageService.set('ownKey1', 1);
|
||||
$document.cookie = 'username=John Doe';
|
||||
localStorageService.clearAll();
|
||||
expect(localStorageService.get('ownKey1')).toEqual(null);
|
||||
expect($document.cookie).not.toEqual('');
|
||||
}));
|
||||
|
||||
it('should be broadcast on adding item', function() {
|
||||
module(setNotify(true, false));
|
||||
inject(function($rootScope, localStorageService) {
|
||||
var spy = spyOn($rootScope, '$broadcast');
|
||||
localStorageService.set('a8m', 'foobar');
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should be broadcast on removing item', function() {
|
||||
module(setNotify(false, true));
|
||||
inject(function($rootScope, localStorageService) {
|
||||
var spy = spyOn($rootScope, '$broadcast');
|
||||
localStorageService.remove('a8m', 'foobar');
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Date.prototype.addDays = function(days) {
|
||||
var date = new Date(this.getTime());
|
||||
date.setDate(date.getDate() + days);
|
||||
return date.toUTCString();
|
||||
};
|
||||
});
|
||||
|
||||
//cookie disabled
|
||||
describe('No Cookie', function() {
|
||||
|
||||
beforeEach(module('LocalStorageModule', function($provide) {
|
||||
$provide.value('$window', {
|
||||
navigator: {
|
||||
cookieEnabled: false
|
||||
}
|
||||
});
|
||||
$provide.value('$document', {
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
it('cookie.isSupported should be false if cookies are disabled', inject(
|
||||
expectCookieSupporting(false)
|
||||
));
|
||||
});
|
||||
});
|
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
describe('Tests functionality of the localStorage module', function() {
|
||||
var ls, p, store = [];
|
||||
|
||||
beforeEach(module('LocalStorageModule', function(localStorageServiceProvider) {
|
||||
p = localStorageServiceProvider;
|
||||
}));
|
||||
|
||||
beforeEach(inject(function(_localStorageService_) {
|
||||
ls = _localStorageService_;
|
||||
ls.clearAll();
|
||||
expect(ls.keys()).toEqual([]);
|
||||
}));
|
||||
|
||||
it('A key should be derived to <prefix>.<key>', function() {
|
||||
var key = "foo";
|
||||
expect(ls.deriveKey(key)).toBe("ls." + key);
|
||||
});
|
||||
|
||||
it('Should be able to replace a key multiple times', function() {
|
||||
var key = "foo",
|
||||
expectedValues = [ "bar", "zoo", "aoo" ];
|
||||
|
||||
for (var expectedValue in expectedValues) {
|
||||
ls.set(key, expectedValue);
|
||||
expect(ls.get(key)).toBe(expectedValue);
|
||||
expect(ls.keys()).toEqual([key]);
|
||||
}
|
||||
});
|
||||
|
||||
it('Should delete a value from my local storage', function() {
|
||||
var key = "foo",
|
||||
expectedValue = "bar";
|
||||
|
||||
ls.set(key, expectedValue);
|
||||
expect(ls.get(key)).toBe(expectedValue);
|
||||
expect(ls.keys()).toEqual([key]);
|
||||
|
||||
expect(ls.remove(key)).toBe(true);
|
||||
expect(ls.get(key)).toBe(null);
|
||||
expect(ls.keys()).toEqual([]);
|
||||
});
|
||||
|
||||
it('Should add a integer value to my local storage', function() {
|
||||
var key = "test",
|
||||
expectedValue = 234;
|
||||
ls.set(key, expectedValue);
|
||||
//Since localStorage makes the value a string, we look for the '234' and not 234
|
||||
expect(ls.get(key)).toBe(expectedValue.toString());
|
||||
expect(ls.keys()).toEqual([key]);
|
||||
});
|
||||
|
||||
it('Should add a String value to my local storage', function() {
|
||||
var key = "foo",
|
||||
expectedValue = "bar";
|
||||
ls.set(key, expectedValue);
|
||||
expect(ls.get(key)).toBe(expectedValue);
|
||||
expect(ls.keys()).toEqual([key]);
|
||||
});
|
||||
|
||||
it('Should add a JSON value to my local storage', function() {
|
||||
var key = "test",
|
||||
expectedValue = { key: 'val' };
|
||||
ls.set(key, expectedValue);
|
||||
|
||||
var res = ls.get(key);
|
||||
expect(res).toEqual(expectedValue);
|
||||
expect(res.key).toBe('val');
|
||||
expect(ls.keys()).toEqual([key]);
|
||||
});
|
||||
|
||||
it('Should allow me to set a prefix', function() {
|
||||
|
||||
var expectedPrefix = "myPref";
|
||||
|
||||
p.setPrefix(expectedPrefix);
|
||||
expect(p.prefix).toBe(expectedPrefix);
|
||||
|
||||
});
|
||||
|
||||
it('Should allow me to set the cookie values', function() {
|
||||
p.setStorageCookie(60, '/path');
|
||||
expect(p.cookie.expiry).toBe(60);
|
||||
expect(p.cookie.path).toBe('/path');
|
||||
});
|
||||
});
|
Reference in New Issue