UNPKG

24 kBJavaScriptView Raw
1/*
2 Loki Angular Adapter (need to include this script to use it)
3 * @author Joe Minichino <joe.minichino@gmail.com>
4 *
5 * A lightweight document oriented javascript database
6 */
7(function (root, factory) {
8 if (typeof define === 'function' && define.amd) {
9 // AMD. Register as an anonymous module.
10 define(['angular', 'lokijs'], factory);
11 } else if (typeof exports === 'object') {
12 // CommonJS
13 module.exports = factory();
14 } else {
15 // Browser globals
16 root.lokiAngular = factory(
17 root.angular,
18 // Use thirdParty.loki if available to cover all legacy cases
19 root.thirdParty && root.thirdParty.loki ?
20 root.thirdParty.loki : root.loki
21 );
22 }
23}(this, function (angular, lokijs) {
24 var module = angular.module('lokijs', [])
25 .factory('Loki', Loki)
26 .service('Lokiwork', Lokiwork);
27
28 function Loki() {
29 return loki;
30 }
31 Lokiwork.$inject = ['Loki', '$q', '$injector', '$window'];
32
33 function Lokiwork(Loki, $q, $injector, $window) {
34 var vm = this;
35 vm.checkStates = checkStates;
36 var statesChecked = false;
37 var db;
38 var userDbPreference = '';
39 var userPrefJsonFile = 0;
40 var numOfJsonDatabases = 0;
41 var dbitems = [];
42 var lokidbs = [];
43 vm.dbExists = dbExists;
44 vm.closeDb = closeDb;
45 vm.closeAllDbs = closeAllDbs;
46 vm.getCollection = getCollection;
47 vm.addCollection = addCollection;
48 vm.removeCollection = removeCollection;
49 vm.getDoc = getDoc;
50 vm.updateDoc = updateDoc;
51 vm.updateCurrentDoc = updateCurrentDoc;
52 vm.setCurrentDoc = setCurrentDoc;
53 vm.getCurrentDoc = getCurrentDoc;
54 vm.deleteDocument = deleteDocument;
55 vm.deleteCurrentDoc = deleteCurrentDoc;
56 vm.deleteDatabase = deleteDatbase;
57 vm.addDocument = addDocument;
58 vm.insertItemInDoc = insertItemInDoc;
59 var currentDoc = {};
60 var currentColl = {};
61 numOfJsonDatabases = getNumberOfJsonDatabases();
62
63 function getCurrentDoc() {
64 return currentDoc;
65 }
66
67 function deleteDatbase(data) {
68 localStorage.removeItem(data);
69 }
70
71 function deleteDocument(dbName, collName, doc) { //doc should be in {name:value} format
72 return $q(function (resolve, reject) {
73 userDbPreference = dbName;
74 _getem('delete_doc', dbName, collName, doc)
75 .then(function (data) {
76 currentDoc = {};
77 resolve(data);
78 }, function(data){
79 reject(data);
80 });
81 });
82 }
83
84
85 function insertItemInDoc(item) {
86 return $q(function (resolve, reject) {
87 _getem('insert_item_in_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, "", item)
88 .then(function (data) {
89 resolve(data);
90 }, function (data) {
91 reject(data);
92 });
93 });
94 }
95
96 function deleteCurrentDoc() {
97 return $q(function (resolve, reject) {
98 _getem('delete_current_doc')
99 .then(function (data) {
100 resolve(data);
101 }, function (data) {
102 reject(data);
103 });
104 });
105 }
106
107 function addDocument(dbName, collName, newDoc) {
108 return $q(function (resolve, reject) {
109 userDbPreference = dbName;
110 _getem('create_doc', dbName, collName, "", "", newDoc)
111 .then(function (data) {
112 currentDoc.dbName = dbName;
113 currentDoc.collName = collName;
114 currentDoc.doc = data;
115 currentDoc.lokiNum = data[0].$loki;
116 resolve(data[0]);
117 }, function(data){
118 reject(data);
119 });
120 });
121 }
122
123 function setCurrentDoc(dbName, collName, docName) {
124 return $q(function (resolve, reject) {
125 userDbPreference = dbName;
126 _getem('set_doc', dbName, collName, docName)
127 .then(function (data) {
128 currentDoc.dbName = dbName;
129 currentDoc.collName = collName;
130 currentDoc.doc = data;
131 currentDoc.lokiNum = data[0].$loki;
132 resolve(data[0]);
133 }, function(data){
134 reject(data);
135 });
136 });
137 }
138
139 function updateCurrentDoc(thekey, thevalue) {
140 return $q(function (resolve, reject) {
141 if (currentDoc) {
142 _getem('update_current_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, thekey, thevalue)
143 .then(function (data) {
144 resolve(data[0]);
145 }, function(data){
146 reject(data);
147 });
148 } else {
149 reject("you have to set a current doc first, use: setCurrentDoc(dbName, collName, docName)");
150 }
151 });
152 }
153
154 function updateDoc(dbName, collName, docName, thekey, thevalue) {
155 return $q(function (resolve, reject) {
156 userDbPreference = dbName;
157 if (currentDoc) {
158 _getem('update_doc', dbName, collName, docName, thekey, thevalue)
159 .then(function (data) {
160 resolve(data[0]);
161 }, function(data){
162 reject(data);
163 });
164 } else {
165 reject("bad, check parameters)");
166 }
167 });
168 }
169
170 function getDoc(dbName, collName, docName) {
171 return $q(function (resolve, reject) {
172 userDbPreference = dbName;
173 _getem('get_doc', dbName, collName, docName)
174 .then(function (data) {
175 currentDoc.dbName = dbName;
176 currentDoc.collName = collName;
177 currentDoc.doc = data;
178 currentDoc.lokiNum = data[0].$loki;
179 resolve(data[0]);
180 }, function(data){
181 reject(data);
182 });
183 });
184 }
185
186 function getCollection(dbName, collName) {
187 return $q(function (resolve, reject) {
188 userDbPreference = dbName;
189 _getem('get_collection', dbName, collName)
190 .then(function (data) {
191 currentColl.dbName = dbName;
192 currentColl.collName = collName;
193 resolve(data);
194 }, function(data){
195 reject(data);
196 });
197 });
198 }
199
200 function removeCollection(dbName, collName) {
201 return $q(function (resolve, reject) {
202 userDbPreference = dbName;
203 _getem('remove_collection', dbName, collName)
204 .then(function (data) {
205 currentColl = {};
206 resolve(data);
207 }, function(data){
208 reject(data);
209 });
210 });
211 }
212
213 function addCollection(collData) {
214 return $q(function (resolve, reject) {
215 var dbobj = breakdown_components(collData);
216 userDbPreference = collData[dbobj.db];
217 _getem('add_collection', userDbPreference, '', '', '', collData)
218 .then(function (data) {
219 currentColl.dbName = userDbPreference;
220 resolve(data);
221 }, function(data){
222 reject(data);
223 });
224 });
225 }
226
227 function _getem(operation, dbName, collName, docName, thekey, thevalue) {
228 return $q(function (resolve, reject) {
229 if (db) {
230 if (db.filename === dbName) {
231 getdata();
232 } else {
233 loadDb(dbName)
234 .then(function () {
235 getdata();
236 });
237 }
238 } else {
239 if (statesChecked) {
240 loadDb(dbName)
241 .then(function () {
242 getdata();
243 });
244 } else {
245 checkStates().then(function () {
246 getdata();
247 }, function(data){
248 reject(data);
249 });
250 }
251 }
252
253
254
255 function getdata() {
256 var found;
257
258 if (operation === 'update_doc' || operation === 'insert_item_in_doc') {
259 db.loadDatabase(dbName);
260 var coll = db.getCollection(collName);
261
262 //docName is not simply a docname, this is an object like: {name: 'user settings'}
263 for(var i in docName) {
264 currentDoc.key = i;
265 currentDoc.value = docName[i];
266 }
267 for (var x = 0; x < coll.data.length; x++){
268 if (coll.data[x][currentDoc.key] === currentDoc.value){
269 currentDoc.lokiNum = coll.data[x].$loki;
270 }
271 }
272 found = coll.get(parseInt(currentDoc.lokiNum, 10));
273
274 if (operation === 'update_doc') {
275 found[thekey] = thevalue;
276 coll.update(found);
277 } else {
278 found.insert(thevalue);
279 }
280 db.save();
281 resolve(true);
282 }
283 else if(operation === 'update_current_doc'){
284 db.loadDatabase(dbName);
285 var coll0 = db.getCollection(collName);
286 found = coll0.get(parseInt(currentDoc.lokiNum, 10));
287 found[thekey] = thevalue;
288 coll0.update(found);
289
290 db.save();
291 resolve(true);
292 }
293 else if (operation === 'delete_current_doc' || operation === 'delete_doc') {
294 db.loadDatabase(dbName);
295 var coll6 = db.getCollection(collName);
296 if(operation === 'delete_doc'){
297 for(var j in docName) {
298 currentDoc.key = j;
299 currentDoc.value = docName[j];
300 }
301 for (var y = 0; y < coll6.data.length; y++){
302 if (coll6.data[y][currentDoc.key] === currentDoc.value){
303 currentDoc.lokiNum = coll6.data[y].$loki;
304 }
305 }
306 }
307 coll6.remove(currentDoc.lokiNum);
308 db.save();
309 resolve(true);
310 }
311 else if (operation === 'get_doc' || operation === 'set_doc') {
312 db.loadDatabase(dbName);
313 var coll1 = db.getCollection(collName);
314 found = coll1.find(docName);
315 resolve(angular.fromJson(found));
316 } else if (operation === 'get_collection') {
317 db.loadDatabase(dbName);
318 var coll2 = db.getCollection(collName);
319 resolve(angular.fromJson(coll2));
320 } else if (operation === 'remove_collection') {
321 db.loadDatabase(dbName);
322 db.removeCollection(collName);
323 //coll = db.getCollection(collName);
324 db.save(function () {
325 resolve('collection deleted');
326 });
327 } else if (operation === 'add_collection') {
328 db.loadDatabase(dbName);
329 var dbobj = breakdown_components(thevalue);
330
331 for (var w=0; w< dbobj.coll_array.length; w++){
332 var items = db.addCollection(thevalue[dbobj.coll_array[w].coll]);
333 items.insert(thevalue[dbobj.coll_array[w].docs]);
334 }
335
336 db.save(function () {
337 resolve('collection(s) added');
338 });
339
340 } else if (operation === 'create_doc') {
341 db.loadDatabase(dbName);
342 var coll3 = db.getCollection(collName);
343 coll3.insert(thevalue);
344 db.save(function () {
345 var found = coll3.find({
346 name: thevalue.name
347 });
348 resolve(angular.fromJson(found));
349 });
350
351 }
352 // _getem('delete_doc', dbName, collName, "", "", doc)
353 else if (operation === 'delete_current_doc') {
354 var coll5 = db.getCollection(currentDoc.collName);
355 if (!coll5) {
356 reject('You forgot to specify a current doc first');
357 } else {
358 coll5.remove(parseInt(currentDoc.lokiNum, 10));
359 db.save();
360 resolve(true);
361 }
362 }
363 }
364 });
365 }
366
367 function dbExists(databaseName) {
368 var value = window.localStorage.getItem(databaseName);
369 if (value) {
370 return true;
371 } else {
372 return false;
373 }
374 }
375
376 function closeAllDbs() {
377 return $q(function (resolve, reject) {
378 var current = 0;
379 for (var x = 0; x < lokidbs.length; x++) {
380 current++;
381 lokidbs[x].close();
382 if (x === (lokidbs.length - 1)) {
383 resolve();
384 }
385 }
386 });
387 }
388
389 function closeDb(databaseName) {
390 return $q(function (resolve, reject) {
391
392 for (var x = 0; x < lokidbs.length; x++) {
393 if (lokidbs.filename === databaseName) {
394 lokidbs[x].close();
395 resolve();
396 break;
397 }
398 }
399
400 });
401 }
402
403
404 function checkStates() {
405 return $q(function (resolve, reject) {
406 if (dbitems.length === 0) {
407 initialiseAll().then(function () {
408 console.log('had to initialize all dbs');
409 statesChecked = true;
410 resolve();
411 }, function (data) {
412 reject(data);
413 });
414 } else {
415 console.log('db list already initialized');
416 resolve();
417 }
418 });
419 }
420
421 function firstFewItemsOfDbList() {
422 return $q(function (resolve, reject) {
423 for (var x = 0; x >= 0; x++) {
424 if ($injector.has('json' + (x + 1))) {
425 var item = {};
426 var setting = $injector.get('json' + (x + 1));
427 var dbobj = breakdown_components(setting);
428 if (setting[dbobj.db] === userDbPreference) { //userDbPreference is the name
429 userPrefJsonFile = x + 1; //userPrefJsonFile is the index
430 if (x === (numOfJsonDatabases - 1)) {
431 resolve();
432 }
433 } else {
434 item.filename = dbobj.db;
435 item.json = x + 1;
436 dbitems.push(item);
437 if (x === (numOfJsonDatabases - 1)) {
438 resolve();
439 }
440 }
441 }
442 else {
443 resolve();
444 break;
445 }
446 }
447 });
448 }
449
450 function initialiseDbList() {
451 return $q(function (resolve, reject) {
452 firstFewItemsOfDbList()
453 .then(function () {
454 if (userPrefJsonFile === 0){
455 reject('Oops!, you didn\'t specify any starting document');
456 }
457 var currentdb = $injector.get('json' + userPrefJsonFile);
458 var item = {};
459 var dbobj = breakdown_components(currentdb);
460 item.filename = dbobj.db;
461 item.json = userPrefJsonFile;
462 dbitems.push(item);
463 resolve();
464 });
465 });
466 }
467
468 function getNumberOfJsonDatabases() {
469 if (numOfJsonDatabases >= 1) {
470 return numOfJsonDatabases;
471 } else {
472 for (var x = 0; x >= 0; x++) {
473 if ($injector.has('json' + (x + 1))) {
474 numOfJsonDatabases++;
475 }
476 else {
477 break;
478 }
479
480 }
481 return numOfJsonDatabases;
482 }
483 }
484
485 var still_running = false;
486 var current_iteration = 1;
487
488 function initialiseAll() {
489 return $q(function (resolve, reject) {
490 initialiseDbList()
491 .then(function () {
492
493 function iterate_me() {
494 if ($injector.has('json' + dbitems[current_iteration - 1].json)) {
495 var setting = $injector.get('json' + dbitems[current_iteration - 1].json);
496
497 console.log('number = ' + current_iteration);
498 var set = angular.fromJson(setting);
499 still_running = true;
500 initiateDb(set)
501 .then(function () {
502 //lokidbs.push(angular.copy(db));
503 if (!doesDBAlreadyExistInArray(db.filename)) {
504 lokidbs.push(angular.copy(db));
505 }
506 still_running = false;
507 if (current_iteration === (dbitems.length)) {
508 resolve();
509 } else {
510 current_iteration++;
511 iterate_me();
512 return;
513 }
514 });
515 }
516 }
517 iterate_me();
518 }, function(data){
519 reject(data);
520 });
521 });
522 }
523
524 function doesDBAlreadyExistInArray(dbname) {
525 var answer = false;
526 for (var x = 0; x < lokidbs.length; x++) {
527 if (lokidbs[x].filename === dbname) {
528 answer = true;
529 }
530 }
531 return answer;
532 }
533
534 function getIndexOfDbItem(dbname) {
535 var answer = -1;
536 for (var x = 0; x < numOfJsonDatabases; x++) {
537 if (dbitems[x].filename === dbname) {
538 answer = x;
539 }
540 }
541 return answer;
542 }
543
544 function loadDb(databaseName) {
545 return $q(function (resolve, reject) {
546 for (var x = 0; x < lokidbs.length; x++) {
547 if (lokidbs[x].filename === databaseName) {
548 db = lokidbs[x];
549 resolve();
550 }
551 }
552 });
553 }
554
555
556
557 function initiateDb(database) {
558 return $q(function (resolve, reject) {
559 var dbobj = breakdown_components(database);
560 var db_does_exist = false;
561 if (dbExists(database[dbobj.db])) {
562 db_does_exist = true;
563 }
564 db = new loki(database[dbobj.db], {
565 autoload: true,
566 autoloadCallback: loadHandler, //loadHandler, //for some reason this has to be called like this
567 autosave: true,
568 autosaveInterval: 10000
569 });
570
571 function loadHandler() {
572 if (db_does_exist) {
573
574 resolve();
575 } else {
576 var dbobj = breakdown_components(database);
577 for(var x = 0; x < dbobj.coll_array.length; x++){
578 var items = db.addCollection(database[dbobj.coll_array[x].coll]);
579 items.insert(database[dbobj.coll_array[x].docs]);
580 }
581 db.save();
582 resolve();
583 }
584 }
585 });
586 }
587 function breakdown_components(db_obj){
588 var iterate = 1;
589 var db_id = '';
590 var coll_id = "";
591 var doc_id = "";
592 var collections = [];
593 for(var i in db_obj){
594 if (iterate > 1){
595 if(isEven(iterate)){
596 coll_id = i;
597 }
598 else{
599 doc_id = i;
600 var tempobj = {coll: coll_id, docs: doc_id};
601 collections.push(tempobj);
602 }
603 }
604 else {
605 db_id = i;
606 }
607 iterate ++;
608 }
609
610 var dataobj = {db: db_id, coll_array: collections};
611 return dataobj;
612 }
613 function isEven(n) {
614 return n % 2 === 0;
615 }
616 function isOdd(n) {
617 return Boolean(n % 2);
618 }
619 }
620 return module;
621}));