UNPKG

10.3 kBJavaScriptView Raw
1/*
2 * localdb
3 * (c) 2015
4 * github.com/egoist/localdb
5 */
6
7'use strict';
8
9var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
10
11function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
12
13(function () {
14
15 var defaultOpts = { limit: 0, sortBy: 'index', sort: 1, skip: 0 };
16
17 var definition = function definition(W, LS) {
18 var LocalDB = (function () {
19 function LocalDB(name) {
20 var type = arguments.length <= 1 || arguments[1] === undefined ? 'Array' : arguments[1];
21 var timestamp = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
22
23 _classCallCheck(this, LocalDB);
24
25 if (typeof name === 'string') {
26 this.db = name;
27 this.type = type;
28 this.timestamp = timestamp;
29 } else if (typeof name === 'object') {
30 var opts = name;
31 this.db = opts.name;
32 this.type = opts.type || 'Array';
33 this.timestamp = opts.timestamp || false;
34 }
35 this.populate_keys = null;
36 }
37
38 _createClass(LocalDB, [{
39 key: 'get',
40 value: function get(where) {
41 // where maps to key or index, depending on the type if Object or Array
42 var collection = JSON.parse(LS.getItem(this.db));
43 if (!where && typeof where !== 'number') return collection;else if (typeof collection === 'undefined' || !collection) return null;else return collection[where];
44 }
45 }, {
46 key: 'findOne',
47 value: function findOne(query) {
48 return this.find(query, {
49 limit: 1
50 });
51 }
52 }, {
53 key: 'find',
54 value: function find(query) {
55 var _this = this;
56
57 var opts = arguments.length <= 1 || arguments[1] === undefined ? defaultOpts : arguments[1];
58
59 if (this.type !== 'Array') {
60 return console.error('The .findOne method only works if the database is an Array!');
61 }
62
63 opts.limit = opts.limit || defaultOpts.limit;
64 opts.sortBy = opts.sortBy || defaultOpts.sortBy;
65 opts.sort = opts.sort || defaultOpts.sort;
66 opts.skip = opts.skip || defaultOpts.skip;
67
68 var collection = this.get() || [];
69 if (query) {
70 collection = collection.filter(function (obj) {
71 var has = [];
72 for (var key in query) {
73 has.push(obj[key] === query[key]);
74 }
75 if (arrayEachTrue(has)) {
76 return true;
77 } else {
78 return false;
79 }
80 });
81 }
82 if (opts.limit === 1 && opts.skip === 0) {
83 collection = collection[0];
84 } else {
85
86 collection = collection.sort(function (a, b) {
87 if (a[opts.sortBy] < b[opts.sortBy]) {
88 return -opts.sort;
89 } else if (a[opts.sortBy] > b[opts.sortBy]) {
90 return opts.sort;
91 } else {
92 return 0;
93 }
94 });
95
96 if (opts.limit === 0) {
97 collection = collection.slice(opts.skip);
98 } else {
99 collection = collection.slice(opts.skip, opts.limit + opts.skip);
100 }
101 }
102
103 var populate = function populate(collection) {
104
105 if (_this.populate_keys && _this.populate_keys.length > 0) _this.populate_keys.forEach(function (key) {
106 var ref = collection[key];
107 if (ref) {
108 var db = new LocalDB(ref.__className, 'Array');
109 var temp = db.findOne({ '_id': ref.objectId });
110 collection[key] = temp;
111 }
112 });
113 return collection;
114 };
115
116 if (Array.isArray(collection)) {
117 collection.forEach(function (c) {
118 c = populate(c);
119 });
120 } else if (typeof collection === 'object') {
121 collection = populate(collection);
122 }
123
124 this.populate_keys = null;
125
126 return collection;
127 }
128 }, {
129 key: 'add',
130 value: function add(obj) {
131 if (this.type !== 'Array') {
132 console.error('The .add method only works if the database is an Array!');
133 }
134 var collection = this.get() || [];
135 var index = 0;
136 if (collection && collection.length > 0) {
137 index = collection.length;
138 }
139 obj = this.initObj(index, obj);
140 collection.push(obj);
141 this.override(collection);
142 return this;
143 }
144 }, {
145 key: 'initObj',
146 value: function initObj(index, obj) {
147 obj.index = index;
148 if (!obj._id) {
149 obj._id = objectId();
150 }
151 if (this.timestamp) {
152 if (!obj.createdAt) {
153 obj.createdAt = new Date();
154 }
155 obj.updatedAt = new Date();
156 }
157 return obj;
158 }
159 }, {
160 key: 'set',
161 value: function set(key, value) {
162 // works if db is object
163 if (this.type !== 'Object') {
164 console.error('The .set method only works if the database is an Object!');
165 } else {
166 var collection = this.get() || {};
167 collection[key] = value;
168 this.override(collection);
169 }
170 return this;
171 }
172 }, {
173 key: 'inc',
174 value: function inc(key) {
175 var value = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
176
177 return this.incOrDec('inc', key, value);
178 }
179 }, {
180 key: 'dec',
181 value: function dec(key) {
182 var value = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
183
184 return this.incOrDec('dec', key, value);
185 }
186 }, {
187 key: 'incOrDec',
188 value: function incOrDec(type, key) {
189 var value = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];
190
191 if (this.type !== 'Object') {
192 console.error('The .set method only works if the database is an Object!');
193 } else {
194 var collection = this.get() || {};
195 if (type === 'inc') {
196 collection[key] = (collection[key] || 0) + value;
197 } else if (type === 'dec') {
198 collection[key] = (collection[key] || 0) - value;
199 }
200 this.override(collection);
201 }
202 return this;
203 }
204 }, {
205 key: 'save',
206 value: function save(obj) {
207 if (this.type !== 'Array') {
208 console.error('The .save method only works if the database is an Array!');
209 }
210 var collection = this.get();
211 if (collection[obj.index]._id === obj._id) {
212 collection[obj.index] = obj;
213 this.override(collection);
214 }
215 return this;
216 }
217 }, {
218 key: 'extend',
219 value: function extend(id) {
220 if (!id) {
221 return console.error('You should provide an objectId to reference');
222 }
223 return {
224 __type: 'Pointer',
225 __className: this.db,
226 objectId: id
227 };
228 }
229 }, {
230 key: 'populate',
231 value: function populate() {
232 for (var _len = arguments.length, keys = Array(_len), _key = 0; _key < _len; _key++) {
233 keys[_key] = arguments[_key];
234 }
235
236 this.populate_keys = keys;
237 return this;
238 }
239 }, {
240 key: 'override',
241 value: function override(collection) {
242 var reinit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
243
244 if (this.type === 'Array' && reinit) {
245 for (var i = 0; i < collection.length; i++) {
246 collection[i] = this.initObj(i, collection[i]);
247 }
248 }
249 LS.setItem(this.db, JSON.stringify(collection));
250 return this;
251 }
252 }, {
253 key: 'remove',
254 value: function remove(key, value) {
255 var collection = this.get();
256
257 if (this.type === 'Array') {
258 if (collection.length === 0) {
259 return this;
260 }
261 collection = collection.filter(function (obj) {
262 if (obj[key] === value) {
263 return false;
264 } else {
265 return true;
266 }
267 });
268 for (var i = 0; i < collection.length; i++) {
269 collection[i].index = i;
270 }
271 } else if (this.type === 'Object') {
272 delete collection[key];
273 }
274
275 LS.setItem(this.db, JSON.stringify(collection));
276 return this;
277 }
278 }, {
279 key: 'destroy',
280 value: function destroy() {
281 LS.removeItem(this.db);
282 return this;
283 }
284 }]);
285
286 return LocalDB;
287 })();
288
289 return LocalDB;
290 };
291
292 function arrayEachTrue(array) {
293 for (var i = 0; i < array.length; i++) {
294 if (!array[i]) {
295 return false;
296 }
297 }
298 return true;
299 }
300
301 function objectId() {
302 var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
303 return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function () {
304 return (Math.random() * 16 | 0).toString(16);
305 }).toLowerCase();
306 }
307
308 ;(function (context, name, definition) {
309 if (typeof module !== 'undefined') {
310 module.exports = definition;
311 } else if (typeof context !== 'undefined') {
312 context[name] = definition;
313 }
314 })(window, 'localdb', definition(window, window.localStorage));
315})();
\No newline at end of file