-
Notifications
You must be signed in to change notification settings - Fork 1
/
angular-odm.js
695 lines (525 loc) · 24.6 KB
/
angular-odm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/**
* @license AngularJS v1.4.7
* (c) 2010-2015 Google, Inc. http://angularjs.org
* License: MIT
*/
(function (window, angular, undefined) {
//ECMA6 Strict
'use strict';
/**
* @ngdoc module
* @name ngOdm
* @description
* AngularJS Object Database Model
*/
angular.module('ngOdm', ['ng']).
/**
* @ngdoc odm
* @name $odm
*/
provider('$odm', ['ODM', function $odmProvider(ODM) {
// ################################################### Objects // ##############################################
//Init odm object which will be returned by this provider.
var odm = {
db: null,
model: null
};
/**
* @ngdoc service
* @name $odm
*
* @description
* Provides read/write access to browser's cookies.
*/
this.$get = [function () {
/**
* Database object
*
* @name odm.db
* @returns {odm.db}
*/
odm.db = function () {
// ############################################# Functions // ##########################################
/**
* DB init
* Creates tables based on configured tables in config -> ODM.dbSchema
*
* @return {self|false}
*
*/
self.init = function () {
//create locale storage database if it does not exists.
if (ODM.dbSchema === undefined || ODM.dbSchema.name === undefined) {
console.error('#angular-odm ! ODM.dbSchema.name not defined. Failed to initialize localeStorageDb');
return false;
} else {
self.localStorageDBProvider = new localStorageDB(ODM.dbSchema.name, localStorage);
}
//move through all configured tables
angular.forEach(ODM.dbSchema.tables, function (table) {
//Init
var columns = [];
//collect relation columns
angular.forEach(table.columns, function (column) {
columns.push(column.name);
});
//check drop statement
if (table.resetOnInit && self.localStorageDBProvider.tableExists(table.name)) {
self.localStorageDBProvider.dropTable(table.name);
//console.info('Table "' + table.name + '" reset done');
}
//create tables query
if ((self.localStorageDBProvider.tableExists(table.name))) {
//console.warn('Table "' + table.name + ' already exists. Skipping create table.');
} else {
if (self.localStorageDBProvider.createTable(table.name, columns)) {
//console.info('Table "' + table.name + '" initialized');
} else {
console.info('#angular-odm ! Cannot create Table "' + table.name);
}
}
});
//commit database to localStorage
self.localStorageDBProvider.commit();
};
//return {db} object
return self;
};
/**
* Model handling
* @returns {{getInstance: model.getInstance}}
*/
odm.model = function () {
// ################################################ Vars // ############################################
var serviceProvider = function () {
/**
* Data store
* @type {Array}
*/
this.data = [];
/**
* Error store
* @type {Array}
*/
this.errors = [];
};
// ############################################# Functions // ##########################################
/**
* Model instance provider handler
* This object is returned on the end of this object
*/
var model = {
getInstance: function () {
return new serviceProvider();
}
};
/**
* Model init function, provides
*
* @param childModel
* @returns {{this}}
*/
serviceProvider.prototype.init = function (childModel) {
//Init
var mergedSelf = {};
//combine js objects
for (var attrname in childModel) {
mergedSelf[attrname] = childModel[attrname];
}
for (var attrname in this) {
mergedSelf[attrname] = this[attrname];
}
//set attributes
angular.forEach(mergedSelf._attributes, function (attribute) {
switch (attribute.type) {
case 'pk':
mergedSelf[attribute.name] = null;
break;
case 'integer':
mergedSelf[attribute.name] = 0;
break;
case 'text':
mergedSelf[attribute.name] = '';
break;
case 'boolean':
mergedSelf[attribute.name] = null;
break;
default:
console.log('Not defined attributes type: "' + attribute.type + '" in model.init');
break;
}
});
return mergedSelf;
};
/**
* Save function
*
* @return boolean / object
*/
serviceProvider.prototype.save = function () {
//Init global self
var self = this;
var insertId;
if (this.validate()) {
//define data to insert
var data = {};
//start async progress
angular.forEach(self._attributes, function (attribute) {
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = self[attribute.name];
break;
case 'text':
data[attribute.name] = self[attribute.name];
break;
case 'boolean':
data[attribute.name] = self[attribute.name];
break;
default:
console.warn('Not defined attributes type: "' + attribute.type + '" in model.save');
break;
}
});
//query db
if (insertId = odm.db().localStorageDBProvider.insert(self._table, data)) {
//setup current record ID
self.ID = insertId;
//commit changes to db
return odm.db().localStorageDBProvider.commit();
}
} else {
return false;
}
};
/**
* Update function
*
* @param {object} attributes Optional keys of fields to update. key : value.
*/
serviceProvider.prototype.update = function (attributes) {
//Init global self
var self = this;
//validate & check if PK to update is given
if (this.validate() && angular.isNumber(this.ID) && !angular.isUndefined(attributes)) {
// define sql statement
var data = {};
//build query
angular.forEach(self._attributes, function (attribute) {
//check if attribute is in scope and overstep if not.
//empty scope = every attribute will be updated
if (Object.keys(self._attributes).length > 0 && angular.isUndefined(attributes[attribute.name])) {
return; //means continue in third party loops
}
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = attributes[attribute.name];
break;
case 'text':
data[attribute.name] = String(attributes[attribute.name]);
break;
case 'boolean':
data[attribute.name] = Boolean(attributes[attribute.name]);
break;
}
});
//update row with current self.ID
odm.db().localStorageDBProvider.update(self._table, {ID: self.ID}, function (row) {
//build query
angular.forEach(data, function (value, key) {
//set new value on given attributes
if (data[key] !== undefined) {
row[key] = data[key];
}
});
// return row to update
return row;
});
//commit changes to db and check result + update model attributes
if (odm.db().localStorageDBProvider.commit()) {
if (angular.isObject(attributes)) {
angular.forEach(attributes, function (value, key) {
self[key] = value;
});
}
return true;
} else {
return false;
}
} else {
return false;
}
};
/**
* Find all items
*
* @return {object}
*/
serviceProvider.prototype.findAll = function () {
var self = this;
//set data
return self.data = odm.db().localStorageDBProvider.queryAll(self._table, {});
};
/**
* Returns total count of rows in database.
*
* @return {number}
*/
serviceProvider.prototype.countAll = function () {
var self = this;
//set data
return odm.db().localStorageDBProvider.queryAll(self._table, {}).length;
};
/**
* Find all rows by attributes. Return single row which was find by attributes
*
* @param {array} attributes
*/
serviceProvider.prototype.findAllByAttributes = function (attributes) {
// define sql statement
var result = {};
//Init global self
var self = this;
// unset currrent data
self.data = [];
this.data = [];
var data = {};
angular.forEach(this._attributes, function (attribute) {
//check if attribute is in scope and overstep if not.
//empty scope = every attribute will be updated
if (Object.keys(attributes).length > 0 && angular.isUndefined(attributes[attribute.name])) {
return; //means continue in third party loops
}
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = attributes[attribute.name];
break;
case 'text':
data[attribute.name] = String(attributes[attribute.name]);
break;
case 'boolean':
data[attribute.name] = Boolean(attributes[attribute.name]);
break;
}
});
return self.data = odm.db().localStorageDBProvider.queryAll(self._table, {"query": data});
};
/**
* Find by attributes. Return single row which was find by attributes
*
* @param {array} attributes
*/
serviceProvider.prototype.findByAttributes = function (attributes) {
var data = {};
var self = this;
//start async progress
angular.forEach(this._attributes, function (attribute) {
//check if attribute is in scope and overstep if not.
//empty scope = every attribute will be updated
if (Object.keys(attributes).length > 0 && angular.isUndefined(attributes[attribute.name])) {
return; //means continue in third party loops
}
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = attributes[attribute.name];
break;
case 'text':
data[attribute.name] = String(attributes[attribute.name]);
break;
case 'boolean':
data[attribute.name] = Boolean(attributes[attribute.name]);
break;
}
});
//query db
var result = odm.db().localStorageDBProvider.queryAll(self._table, {"query": data, limit: 1});
if (result.length > 0 && !angular.isUndefined(result[0].ID)) {
angular.forEach(result[0], function (value, key) {
self[key] = value;
});
}
return result[0];
};
/**
* Count by attributes. Return integer count of detected rows.
*
* @param {array} attributes
*
* @return {int}
*/
serviceProvider.prototype.countByAttributes = function (attributes) {
var data = {};
var self = this;
//start async progress
angular.forEach(this._attributes, function (attribute) {
//check if attribute is in scope and overstep if not.
//empty scope = every attribute will be updated
if (Object.keys(attributes).length > 0 && angular.isUndefined(attributes[attribute.name])) {
return; //means continue in third party loops
}
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = attributes[attribute.name];
break;
case 'text':
data[attribute.name] = String(attributes[attribute.name]);
break;
case 'boolean':
data[attribute.name] = Boolean(attributes[attribute.name]);
break;
}
});
//query db
return odm.db().localStorageDBProvider.queryAll(self._table, {"query": data}).length;
};
/**
* Find entry by primary key
*
* @param {integer} pk
*
* @return boolean
*/
serviceProvider.prototype.findByPk = function (pk) {
var self = this;
//check if pk is a number
if (angular.isNumber(pk)) {
var result = odm.db().localStorageDBProvider.query(this._table, {"ID": pk});
if (result.length > 0 && !angular.isUndefined(result[0].ID)) {
if (result.length > 0 && !angular.isUndefined(result[0].ID)) {
angular.forEach(result[0], function (value, key) {
self[key] = value;
});
}
return result[0];
}
}
return {};
};
/**
* Delete row by primary key
*
* @param {int} pk
*
* @return boolean
*/
serviceProvider.prototype.deleteByPk = function (pk) {
if (angular.isNumber(pk)) {
//delete rows
odm.db().localStorageDBProvider.deleteRows(this._table, {"ID": pk});
//commit changes to db
return odm.db().localStorageDBProvider.commit();
}
return false;
};
/**
* Delete by attributes
*
* @param {arr} attributes
*/
serviceProvider.prototype.deleteByAttributes = function (attributes) {
var data = {};
var self = this;
//start async progress
angular.forEach(this._attributes, function (attribute) {
//check if attribute is in scope and overstep if not.
//empty scope = every attribute will be updated
if (Object.keys(attributes).length > 0 && angular.isUndefined(attributes[attribute.name])) {
return; //means continue in third party loops
}
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
data[attribute.name] = attributes[attribute.name];
break;
case 'text':
data[attribute.name] = String(attributes[attribute.name]);
break;
case 'boolean':
data[attribute.name] = Boolean(attributes[attribute.name]);
break;
}
});
//delete rows
odm.db().localStorageDBProvider.deleteRows(self._table, data);
return odm.db().localStorageDBProvider.commit();
};
/**
* Delete all rows and reset indexies
*/
serviceProvider.prototype.deleteAll = function () {
//Truncate table
if (odm.db().localStorageDBProvider.tableExists(this._table)) {
odm.db().localStorageDBProvider.truncate(this._table);
}
//commit changes to db
return odm.db().localStorageDBProvider.commit();
};
/**
* Validate attributes
*
* @return {boolean}
*/
serviceProvider.prototype.validate = function () {
//clear errors
this.errors = [];
var self = this; // set global function instance
if (odm.db().localStorageDBProvider.tableExists(self._table)) {
//validate every attribute by type
angular.forEach(self._attributes, function (attribute) {
if (!angular.isUndefined(self[attribute.name])) {
switch (attribute.type) {
case 'pk': // do nothing with PK
break;
case 'integer':
if (!angular.isNumber(self[attribute.name])) {
self.errors[attribute.name] = 'Integer expected';
}
break;
case 'text':
if (!angular.isString(self[attribute.name])) {
self.errors[attribute.name] = 'String expected';
}
break;
case 'boolean':
if (typeof(self[attribute.name]) !== "boolean") {
self.errors[attribute.name] = 'Boolean expected';
}
break;
default:
console.log('Not defined attributes type: "' + attribute.type + '"');
break;
}
} else {
self.errors[attribute.name] = 'Attribute ' + attribute.name + ' is undefined. Cannot validate it.';
}
})
} else {
self.errors[attribute.name] = 'Table "' + self._table + '" does not exist in db.';
}
//rewrite errors
this.errors = self.errors;
//return true/false depend on errors found
var result = Object.keys(this.errors).length > 0 ? false : true;
//return result
return result;
};
//auto init database on load
this.db().init();
//return model -> non-singleton model instance object
return model;
};
//return odm object
return odm;
}];
}]);
})(window, window.angular);