Permalink
Browse files

Merge pull request #1 from Talby/oo

Made cookie store object
  • Loading branch information...
2 parents 01c83f8 + 6c08146 commit cf024ad1235bf243958cc28dc84915f5becd5ca7 @chrhicks committed Oct 19, 2011
Showing with 87 additions and 0 deletions.
  1. +87 −0 lib/cookie-storage.js
View
@@ -150,5 +150,92 @@
};
}());
+ scope.CookieStore = scope.CookieStore || (function () {
+ var CookieManager, MAX_COOKIE_LENGTH;
+
+ MAX_COOKIE_LENGTH = 4096;
+ CookieManager = CookieStorage.CookieManager;
+ function CookieStore(namespace) {
+ this.prefix = namespace;
+ this.kvstore = this.loadStores();
+ }
+
+ CookieStore.prototype.persist = function () {
+ var vCookieKey,
+ vCookieVal,
+ index = 0,
+ vCookie = {};
+
+ _.each(this.kvstore, function (value, key) {
+ vCookieKey = this.prefix + index;
+ vCookieVal = vCookie[vCookieKey] || '';
+
+ if (cookieSize(vCookieVal) + entrySize(key) > MAX_COOKIE_LENGTH) {
+ index += 1;
+ }
+
+ vCookieVal += key + '=' + CookieManager.encode(value) + '|';
+ vCookie[vCookieKey] = vCookieVal;
+ });
+
+ this.clearStores();
+
+ _.each(vCookie, function (value, key) {
+ CookieManager.set(key, value);
+ });
+ };
+
+ CookieStore.prototype.listStores = function () {
+ var regEx = new RegExp(this.prefix + "\\d+", "g");
+ return document.cookie.match(regEx) || [];
+ };
+
+ CookieStore.prototype.clearStores = function () {
+ _.each(this.listStores(), function (storeKey) {
+ CookieManager.remove(storeKey);
+ });
+ };
+
+ CookieStore.prototype.loadStores = function () {
+ var cookieVal, parts,
+ kvo = {};
+
+ _.each(this.listStores(), function (storeKey) {
+ cookieVal = CookieManager.get(storeKey);
+ _.each(cookieVal.split('|'), function (pair) {
+ parts = pair.split("=");
+ if (parts[0]) {
+ kvo[parts[0]] = parts[1];
+ }
+ });
+ });
+
+ return kvo;
+ };
+
+ /**
+ * k=val
+ * k.length + '='.length + kvstore[k].length
+ */
+ CookieStore.prototype.entrySize = function (k) {
+ return k.length + 1 + (this.kvstore[k] ? CookieManager.encode(this.kvstore[k]).length : 0);
+ };
+
+ CookieStore.prototype.cookieSize = function (value) {
+ return this.prefix.length + 2 + (value ? CookieManager.encode(value).length : 0);
+ };
+
+ CookieStore.prototype.put = function (k, v) {
+ this.kvstore[k] = v;
+ this.persist();
+ };
+
+ CookieStore.prototype.get = function (k) {
+ return this.kvstore[k];
+ };
+
+ return CookieStore;
+ })();
+
scope.CookieStorage.init();
}(this));

0 comments on commit cf024ad

Please sign in to comment.