blob: c5d6b63367123f0872bcba40f5b99d7dbada76c1 [file] [log] [blame]
// depot.js v0.1.6 | (c) 2013 Michal Kuklis | Licensed under The MIT License
(function(f,h,d){"object"==typeof exports?module.exports=d():"function"==typeof define&&define.amd?define(d):h[f]=d()})("depot",this,function(){function f(b){return b&&JSON.parse(b)}function h(b,a){var c,e;if("function"==typeof b)c=b(a);else for(e in c=!0,b)c&=b[e]===a[e];return c}function d(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function g(b,a){for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}var j={save:function(b){var a;b[this.idAttribute]||(b[this.idAttribute]=
d()+d()+"-"+d()+"-"+d()+"-"+d()+"-"+d()+d()+d());a=b[this.idAttribute]+"";0>this.ids.indexOf(a)&&(this.ids.push(a),this.storageAdaptor.setItem(this.name,this.ids.join(",")));this.storageAdaptor.setItem(this.name+"-"+a,JSON.stringify(b));return b},update:function(b,a){"undefined"==typeof a&&(a=b,b=a[this.idAttribute]);var c=this.get(b);c&&(c=g(c,a),this.save(c));return c},updateAll:function(b){var a=this.all();a.forEach(function(a){a=g(a,b);this.save(a)},this);return a},find:function(b){var a,c,e=
this.name,d=this;return!b?this.all():this.ids.reduce(function(g,j){c=f(d.storageAdaptor.getItem(e+"-"+j));(a=h(b,c))&&g.push(c);return g},[])},get:function(b){return f(this.storageAdaptor.getItem(this.name+"-"+b))},all:function(){var b,a=this,c=this.name;return this.ids.reduce(function(e,d){(b=a.storageAdaptor.getItem(c+"-"+d))&&e.push(f(b));return e},[])},destroy:function(b){var a;a=b[this.idAttribute]?b[this.idAttribute]:b;var c=this.name+"-"+a;b=f(this.storageAdaptor.getItem(c));this.storageAdaptor.removeItem(c);
a=this.ids.indexOf(a);-1!=a&&this.ids.splice(a,1);this.storageAdaptor.setItem(this.name,this.ids.join(","));return b},destroyAll:function(b){for(var a,c,d=this.ids.length-1;0<=d;d--)if(a=this.ids[d],a=this.name+"-"+a,b){if(c=f(this.storageAdaptor.getItem(a)),c=h(b,c))this.storageAdaptor.removeItem(a),this.ids.splice(d,1)}else this.storageAdaptor.removeItem(a);b?this.storageAdaptor.setItem(this.name,this.ids.join(",")):(this.storageAdaptor.removeItem(this.name),this.ids=[])},size:function(){return this.ids.length}};
return function(b,a){var c,d;a=g({idAttribute:"_id",storageAdaptor:localStorage},a);if(!a.storageAdaptor)throw Error("No storage adaptor was found");d=(c=a.storageAdaptor.getItem(b))&&c.split(",")||[];return Object.create(j,{name:{value:b},store:{value:c},ids:{value:d,writable:!0},idAttribute:{value:a.idAttribute},storageAdaptor:{value:a.storageAdaptor}})}});