This repository has been archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-model.js
2872 lines (2759 loc) · 104 KB
/
data-model.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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MOST Web Framework
* A JavaScript Web Framework
* http://themost.io
* Created by Kyriakos Barbounakis<k.barbounakis@gmail.com> on 2014-10-13.
*
* Copyright (c) 2014, Kyriakos Barbounakis k.barbounakis@gmail.com
Anthi Oikonomou anthioikonomou@gmail.com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of MOST Web Framework nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var _ = require("lodash");
var util = require('util');
var sprintf = require('sprintf');
var path = require("path");
var async = require('async');
var qry = require('most-query');
var types = require('./types');
var DataAssociationMapping = require('./types').DataAssociationMapping;
var dataCommon = require('./data-common');
var dataListeners = require('./data-listeners');
var validators = require('./data-validator');
var dataAssociations = require('./data-associations');
var DataNestedObjectListener = require("./data-nested-object-listener").DataNestedObjectListener;
var DataReferencedObjectListener = require("./data-ref-object-listener").DataReferencedObjectListener;
var DataQueryable = require('./data-queryable').DataQueryable;
var DataAttributeResolver = require('./data-queryable').DataAttributeResolver;
var DataObjectAssociationListener = dataAssociations.DataObjectAssociationListener;
var DataModelView = require('./data-model-view').DataModelView;
var DataFilterResolver = require('./data-filter-resolver').DataFilterResolver;
var Q = require("q");
/**
* @param {DataField} field
* @private
*/
function inferTagMapping_(field) {
/**
* @type {DataModel|*}
*/
var self = this;
//validate field argument
if (_.isNil(field)) {
return;
}
//validate DataField.many attribute
if (!(field.hasOwnProperty('many') && field.many === true)) {
return;
}
//check if the type of the given field is a primitive data type
//(a data type that is defined in the collection of data types)
var conf = self.context.getConfiguration(), dataType = conf.dataTypes[field.type];
if (_.isNil(dataType)) {
return;
}
//get associated model name
var name = self.name.concat(_.upperFirst(field.name));
var primaryKey = self.key();
return new DataAssociationMapping({
"associationType": "junction",
"associationAdapter": name,
"cascade": "delete",
"parentModel": self.name,
"parentField": primaryKey.name,
"refersTo": field.name
});
}
/**
* @ignore
* @class
* @constructor
* @augments QueryExpression
*/
function EmptyQueryExpression() {
//
}
/**
* @classdesc DataModel class extends a JSON data model and performs all data operations (select, insert, update and delete) in MOST Data Applications.
<p>
These JSON schemas are in config/models folder:
</p>
<pre class="prettyprint"><code>
/
+ config
+ models
- User.json
- Group.json
- Account.json
...
</code></pre>
<p class="pln">
The following JSON schema presents a typical User model with fields, views, privileges, constraints, listeners, and seeding:
</p>
<pre class="prettyprint"><code>
{
"name": "User", "id": 90, "title": "Application Users", "inherits": "Account", "hidden": false, "sealed": false, "abstract": false, "version": "1.4",
"fields": [
{
"name": "id", "title": "Id", "description": "The identifier of the item.",
"type": "Integer",
"nullable": false,
"primary": true
},
{
"name": "accountType", "title": "Account Type", "description": "Contains a set of flags that define the type and scope of an account object.",
"type": "Integer",
"readonly":true,
"value":"javascript:return 0;"
},
{
"name": "lockoutTime", "title": "Lockout Time", "description": "The date and time that this account was locked out.",
"type": "DateTime",
"readonly": true
},
{
"name": "logonCount", "title": "Logon Count", "description": "The number of times the account has successfully logged on.",
"type": "Integer",
"value": "javascript:return 0;",
"readonly": true
},
{
"name": "enabled", "title": "Enabled", "description": "Indicates whether a user is enabled or not.",
"type": "Boolean",
"nullable": false,
"value": "javascript:return true;"
},
{
"name": "lastLogon", "title": "Last Logon", "description": "The last time and date the user logged on.",
"type": "DateTime",
"readonly": true
},
{
"name": "groups", "title": "User Groups", "description": "A collection of groups where user belongs.",
"type": "Group",
"expandable": true,
"mapping": {
"associationAdapter": "GroupMembers", "parentModel": "Group",
"parentField": "id", "childModel": "User", "childField": "id",
"associationType": "junction", "cascade": "delete",
"select": [
"id",
"name",
"alternateName"
]
}
},
{
"name": "additionalType",
"value":"javascript:return this.model.name;",
"readonly":true
},
{
"name": "accountType",
"value": "javascript:return 0;"
}
], "privileges":[
{ "mask":1, "type":"self", "filter":"id eq me()" },
{ "mask":15, "type":"global", "account":"*" }
],
"constraints":[
{
"description": "User name must be unique across different records.",
"type":"unique",
"fields": [ "name" ]
}
],
"views": [
{
"name":"list", "title":"Users", "fields":[
{ "name":"id", "hidden":true },
{ "name":"description" },
{ "name":"name" },
{ "name":"enabled" , "format":"yesno" },
{ "name":"dateCreated", "format":"moment : 'LLL'" },
{ "name":"dateModified", "format":"moment : 'LLL'" }
], "order":"dateModified desc"
}
],
"eventListeners": [
{ "name":"New User Credentials Provider", "type":"/app/controllers/user-credentials-listener" }
],
"seed":[
{
"name":"anonymous",
"description":"Anonymous User",
"groups":[
{ "name":"Guests" }
]
},
{
"name":"admin@example.com",
"description":"Site Administrator",
"groups":[
{ "name":"Administrators" }
]
}
]
}
</code></pre>
*
* @class
* @property {string} classPath - Gets or sets a string which represents the path of the DataObject subclass associated with this model.
* @property {string} name - Gets or sets a string that represents the name of the model.
* @property {number} id - Gets or sets an integer that represents the internal identifier of the model.
* @property {boolean} hidden - Gets or sets a boolean that indicates whether the current model is hidden or not. The default value is false.
* @property {string} title - Gets or sets a title for this data model.
* @property {boolean} sealed - Gets or sets a boolean that indicates whether current model is sealed or not. A sealed model cannot be migrated.
* @property {boolean} abstract - Gets or sets a boolean that indicates whether current model is an abstract model or not.
* @property {string} version - Gets or sets the version of this data model.
* @property {string} type - Gets or sets an internal type for this model.
* @property {DataCachingType|string} caching - Gets or sets a string that indicates the caching type for this model. The default value is none.
* @property {string} inherits - Gets or sets a string that contains the model that is inherited by the current model.
* @property {DataField[]} fields - Gets or sets an array that represents the collection of model fields.
* @property {DataModelEventListener[]} eventListeners - Gets or sets an array that represents the collection of model listeners.
* @property {Array} constraints - Gets or sets the array of constraints which are defined for this model
* @property {DataModelView[]} views - Gets or sets the array of views which are defined for this model
* @property {DataModelPrivilege[]} privileges - Gets or sets the array of privileges which are defined for this model
* @property {string} source - Gets or sets a string which represents the source database object for this model.
* @property {string} view - Gets or sets a string which represents the view database object for this model.
* @property {DataContext|*} - Gets or sets the data context of this model.
* @property {DataField[]} attributes - Gets an array of DataField objects which represents the collection of model fields (including fields which are inherited from the base model).
* @property {Array} seed - An array of objects which represents a collection of items to be seeded when the model is being generated for the first time
* @constructor
* @augments EventEmitter2
* @param {*=} obj An object instance that holds data model attributes. This parameter is optional.
*/
function DataModel(obj) {
this.hidden = false;
this.sealed = false;
this.abstract = false;
this.version = '0.1';
//this.type = 'data';
this.caching = 'none';
this.fields = [];
this.eventListeners = [];
this.constraints = [];
this.views = [];
this.privileges = [];
//extend model if obj parameter is defined
if (obj)
{
if (typeof obj === 'object')
_.assign(this, obj);
}
/**
* Gets or sets the underlying data adapter
* @type {DataContext}
* @private
*/
var context_ = null;
var self = this;
Object.defineProperty(this, 'context', { get: function() {
return context_;
}, set: function(value) {
context_ = value;
}, enumerable: false, configurable: false});
Object.defineProperty(this, 'sourceAdapter', { get: function() {
return dataCommon.isDefined(self.source) ? self.source : self.name.concat('Base');
}, enumerable: false, configurable: false});
Object.defineProperty(this, 'viewAdapter', { get: function() {
return dataCommon.isDefined(self.view) ? self.view : self.name.concat('Data');
}, enumerable: false, configurable: false});
var silent_ = false;
/**
* Prepares a silent data operation (for query, update, insert, delete etc).
* In a silent execution, permission check will be omitted.
* Any other listeners which are prepared for using silent execution will use this parameter.
* @param {Boolean=} value
* @returns DataModel
*/
this.silent = function(value) {
if (typeof value === 'undefined')
silent_ = true;
else
silent_ = !!value;
return this;
};
Object.defineProperty(this, '$silent', { get: function() {
return silent_;
}, enumerable: false, configurable: false});
var pluralExpression = /([a-zA-Z]+?)([e']s|[^aiou]s)$/;
/**
* @type {Array}
*/
var attributes;
/**
* @private
*/
this._clearAttributes = function() {
attributes = null;
};
/**
* Gets an array of objects that represents the collection of fields for this model.
* This collection contains the fields defined in the current model and its parent.
* @type {Array}
*
*/
Object.defineProperty(this, 'attributes', { get: function() {
//validate self field collection
if (typeof attributes !== 'undefined' && attributes !== null)
return attributes;
//init attributes collection
attributes = [];
//get base model (if any)
var baseModel = self.base(), field;
//enumerate fields
self.fields.forEach(function(x) {
if (typeof x.many === 'undefined') {
if (typeof self.context.getConfiguration().dataTypes[x.type] === 'undefined')
//set one-to-many attribute (based on a naming convention)
x.many = pluralExpression.test(x.name) || (x.mapping && x.mapping.associationType === 'junction');
else
//otherwise set one-to-many attribute to false
x.many = false;
}
//re-define field model attribute
if (typeof x.model === 'undefined')
x.model = self.name;
var clone = x;
//if base model exists and current field is not primary key field
if (baseModel && !x.primary) {
//get base field
field = baseModel.field(x.name);
if (field) {
//clone field
clone = { };
//get all inherited properties
_.assign(clone, field);
//get all overriden properties
_.assign(clone, x);
//set field model
clone.model = field.model;
//set cloned attribute
clone.cloned = true;
}
}
//finally push field
attributes.push(clone);
});
if (baseModel) {
baseModel.attributes.forEach(function(x) {
if (!x.primary) {
//check if member is overridden by the current model
field = self.fields.find(function(y) { return y.name === x.name; });
if (typeof field === 'undefined')
attributes.push(x);
}
});
}
return attributes;
}, enumerable: false, configurable: false});
/**
* Gets the primary key name
* @type String
*/
this.primaryKey = undefined;
//local variable for DateModel.primaryKey
var primaryKey_;
Object.defineProperty(this, 'primaryKey' , { get: function() {
return self.getPrimaryKey();
}, enumerable: false, configurable: false});
this.getPrimaryKey = function() {
if (typeof primaryKey_ !== 'undefined') { return primaryKey_; }
var p = self.fields.find(function(x) { return x.primary==true; });
if (p) {
primaryKey_ = p.name;
return primaryKey_;
}
};
/**
* Gets an array that contains model attribute names
* @type Array
*/
this.attributeNames = undefined;
Object.defineProperty(this, 'attributeNames' , { get: function() {
return self.attributes.map(function(x) {
return x.name;
});
}, enumerable: false, configurable: false});
Object.defineProperty(this, 'constraintCollection' , { get: function() {
var arr = [];
if (_.isArray(self.constraints)) {
//apend constraints to collection
self.constraints.forEach(function(x) {
arr.push(x);
});
}
//get base model
var baseModel = self.base();
if (baseModel) {
//get base model constraints
var baseArr = baseModel.constraintCollection;
if (_.isArray(baseArr)) {
//apend to collection
baseArr.forEach(function(x) {
arr.push(x);
});
}
}
return arr;
}, enumerable: false, configurable: false});
//register listeners
registerListeners_.call(this);
//call initialize method
if (typeof this.initialize === 'function')
this.initialize();
}
util.inherits(DataModel, types.EventEmitter2);
/**
* @returns {Function}
*/
DataModel.prototype.getDataObjectType = function() {
return getDataObjectClass_.bind(this)();
};
/**
* Initializes the current data model. This method is used for extending the behaviour of an install of DataModel class.
*/
DataModel.prototype.initialize = function() {
//
};
/**
* Clones the current data model
* @param {DataContext=} context - An instance of DataContext class which represents the current data context.
* @returns {DataModel} Returns a new DataModel instance
*/
DataModel.prototype.clone = function(context) {
var result = new DataModel(this);
if (context)
result.context = context;
return result;
};
/**
* @private
*/
function registerListeners_() {
//change: 2015-01-19
//description: change default max listeners (10) to 32 in order to avoid node.js message
// for reaching the maximum number of listeners
//author: k.barbounakis@gmail.com
if (typeof this.setMaxListeners === 'function') {
this.setMaxListeners(32);
}
var CalculatedValueListener = dataListeners.CalculatedValueListener,
DefaultValueListener = dataListeners.DefaultValueListener,
DataCachingListener = dataListeners.DataCachingListener,
DataModelCreateViewListener = dataListeners.DataModelCreateViewListener,
DataModelSeedListener = dataListeners.DataModelSeedListener,
DataStateValidatorListener = require('./data-state-validator').DataStateValidatorListener;
//register system event listeners
this.removeAllListeners('before.save');
this.removeAllListeners('after.save');
this.removeAllListeners('before.remove');
this.removeAllListeners('after.remove');
this.removeAllListeners('before.execute');
this.removeAllListeners('after.execute');
this.removeAllListeners('after.upgrade');
//0. Permission Event Listener
var perms = require('./data-permission');
//1. State validator listener
this.on('before.save', DataStateValidatorListener.prototype.beforeSave);
this.on('before.remove', DataStateValidatorListener.prototype.beforeRemove);
//2. Default values Listener
this.on('before.save', DefaultValueListener.prototype.beforeSave);
//3. Calculated values listener
this.on('before.save', CalculatedValueListener.prototype.beforeSave);
//register before execute caching
if (this.caching=='always' || this.caching=='conditional') {
this.on('before.execute', DataCachingListener.prototype.beforeExecute);
}
//register after execute caching
if (this.caching=='always' || this.caching=='conditional') {
this.on('after.execute', DataCachingListener.prototype.afterExecute);
}
//migration listeners
this.on('after.upgrade',DataModelCreateViewListener.prototype.afterUpgrade);
this.on('after.upgrade',DataModelSeedListener.prototype.afterUpgrade);
/**
* change:8-Jun 2015
* description: Set lookup default listeners as obsolete.
*/
////register lookup model listeners
//if (this.type === 'lookup') {
// //after save (clear lookup caching)
// this.on('after.save', DataModelLookupCachingListener.afterSave);
// //after remove (clear lookup caching)
// this.on('after.remove', DataModelLookupCachingListener.afterRemove);
//}
//register configuration listeners
if (this.eventListeners) {
var listenerModulePath;
for (var i = 0; i < this.eventListeners.length; i++) {
var listener = this.eventListeners[i];
//get listener type (e.g. type: require('./custom-listener.js'))
if (listener.type && !listener.disabled)
{
listenerModulePath = listener.type;
if (/^\./.test(listener.type)) {
listenerModulePath = path.resolve(process.cwd(),listener.type);
}
else if (/^\//.test(listener.type)) {
listenerModulePath = path.join(process.cwd(), listener.type);
}
/**
* Load event listener from the defined type
* @type DataEventListener
*/
var m = require(listenerModulePath);
//if listener exports beforeSave function then register this as before.save event listener
if (typeof m.beforeSave === 'function')
this.on('before.save', m.beforeSave);
//if listener exports afterSave then register this as after.save event listener
if (typeof m.afterSave === 'function')
this.on('after.save', m.afterSave);
//if listener exports beforeRemove then register this as before.remove event listener
if (typeof m.beforeRemove === 'function')
this.on('before.remove', m.beforeRemove);
//if listener exports afterRemove then register this as after.remove event listener
if (typeof m.afterRemove === 'function')
this.on('after.remove', m.afterRemove);
//if listener exports beforeExecute then register this as before.execute event listener
if (typeof m.beforeExecute === 'function')
this.on('before.execute', m.beforeExecute);
//if listener exports afterExecute then register this as after.execute event listener
if (typeof m.afterExecute === 'function')
this.on('after.execute', m.afterExecute);
//if listener exports afterUpgrade then register this as after.upgrade event listener
if (typeof m.afterUpgrade === 'function')
this.on('after.upgrade', m.afterUpgrade);
}
}
}
//before execute
this.on('before.execute', perms.DataPermissionEventListener.prototype.beforeExecute);
//before save (validate permissions)
this.on('before.save', perms.DataPermissionEventListener.prototype.beforeSave);
//before remove (validate permissions)
this.on('before.remove', perms.DataPermissionEventListener.prototype.beforeRemove);
}
DataModel.prototype.join = function(model) {
var result = new DataQueryable(this);
return result.join(model);
};
/**
* Initializes a where statement and returns an instance of DataQueryable class.
* @param {String|*} attr - A string that represents the name of a field
* @returns DataQueryable
*/
DataModel.prototype.where = function(attr) {
var result = new DataQueryable(this);
return result.where(attr);
};
/**
* Initializes a full-text search statement and returns an instance of DataQueryable class.
* @param {String} text - A string that represents the text to search for
* @returns DataQueryable
*/
DataModel.prototype.search = function(text) {
var result = new DataQueryable(this);
return result.search(text);
};
/**
* Returns a DataQueryable instance of the current model
* @returns {DataQueryable}
*/
DataModel.prototype.asQueryable = function() {
return new DataQueryable(this);
};
/**
* @private
* @memberOf DataModel
* @param {*} params
* @param {Function} callback
* @returns {*}
*/
function filterInternal(params, callback) {
var self = this;
var parser = qry.openData.createParser(), $joinExpressions = [], view;
if (typeof params !== 'undefined' && params !== null && typeof params.$select === 'string') {
//split select
var arr = params.$select.split(',');
if (arr.length===1) {
//try to get data view
view = self.dataviews(arr[0]);
}
}
parser.resolveMember = function(member, cb) {
if (view) {
var field = view.fields.find(function(x) { return x.property === member });
if (field) { member = field.name; }
}
var attr = self.field(member);
if (attr)
member = attr.name;
if (DataAttributeResolver.prototype.testNestedAttribute.call(self,member)) {
try {
var member1 = member.split("/"),
mapping = self.inferMapping(member1[0]),
expr;
if (mapping && mapping.associationType === 'junction') {
var expr1 = DataAttributeResolver.prototype.resolveJunctionAttributeJoin.call(self, member);
expr = expr1.$expand;
//replace member expression
member = expr1.$select.$name.replace(/\./g,"/");
}
else {
expr = DataAttributeResolver.prototype.resolveNestedAttributeJoin.call(self, member);
}
if (expr) {
var arrExpr = [];
if (_.isArray(expr))
arrExpr.push.apply(arrExpr, expr);
else
arrExpr.push(expr);
arrExpr.forEach(function(y) {
var joinExpr = $joinExpressions.find(function(x) {
if (x.$entity && x.$entity.$as) {
return (x.$entity.$as === y.$entity.$as);
}
return false;
});
if (_.isNil(joinExpr))
$joinExpressions.push(y);
});
}
}
catch (err) {
cb(err);
return;
}
}
if (typeof self.resolveMember === 'function')
self.resolveMember.call(self, member, cb);
else
DataFilterResolver.prototype.resolveMember.call(self, member, cb);
};
parser.resolveMethod = function(name, args, cb) {
if (typeof self.resolveMethod === 'function')
self.resolveMethod.call(self, name, args, cb);
else
DataFilterResolver.prototype.resolveMethod.call(self, name, args, cb);
};
var filter;
if ((params instanceof DataQueryable) && (self.name === params.model.name)) {
var q = new DataQueryable(self);
_.assign(q, params);
_.assign(q.query, params.query);
return callback(null, q);
}
if (typeof params === 'string') {
filter = params;
}
else if (typeof params === 'object') {
filter = params.$filter;
}
try {
parser.parse(filter, function(err, query) {
if (err) {
callback(err);
}
else {
//create a DataQueryable instance
var q = new DataQueryable(self);
q.query.$where = query;
if ($joinExpressions.length>0)
q.query.$expand = $joinExpressions;
//prepare
q.query.prepare();
if (typeof params === 'object') {
//apply query parameters
var select = params.$select,
skip = params.$skip || 0,
orderBy = params.$orderby || params.$order,
groupBy = params.$groupby || params.$group,
expand = params.$expand,
levels = parseInt(params.$levels),
top = params.$top || params.$take;
//select fields
if (typeof select === 'string') {
q.select.apply(q, select.split(',').map(function(x) {
return x.replace(/^\s+|\s+$/g, '');
}));
}
//apply group by fields
if (typeof groupBy === 'string') {
q.groupBy.apply(q, groupBy.split(',').map(function(x) {
return x.replace(/^\s+|\s+$/g, '');
}));
}
if ((typeof levels === 'number') && !isNaN(levels)) {
//set expand levels
q.levels(levels);
}
//set $skip
q.skip(skip);
if (top)
q.query.take(top);
//set $orderby
if (orderBy) {
orderBy.split(',').map(function(x) {
return x.replace(/^\s+|\s+$/g, '');
}).forEach(function(x) {
if (/\s+desc$/i.test(x)) {
q.orderByDescending(x.replace(/\s+desc$/i, ''));
}
else if (/\s+asc/i.test(x)) {
q.orderBy(x.replace(/\s+asc/i, ''));
}
else {
q.orderBy(x);
}
});
}
if (expand) {
var resolver = require("./data-expand-resolver");
var matches = resolver.testExpandExpression(expand);
if (matches && matches.length>0) {
q.expand.apply(q, matches);
}
}
//return
callback(null, q);
}
else {
//and finally return DataQueryable instance
callback(null, q);
}
}
});
}
catch(e) {
return callback(e);
}
}
/**
* @async
* Applies open data filter, ordering, grouping and paging params and returns a data queryable object
* @param {String|{$filter:string=, $skip:number=, $levels:number=, $top:number=, $take:number=, $order:string=, $inlinecount:string=, $expand:string=,$select:string=, $orderby:string=, $group:string=, $groupby:string=}} params - A string that represents an open data filter or an object with open data parameters
* @param {Function=} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain an instance of DataQueryable class.
* @returns Promise<DataQueryable>|*
* @example
context.model('Order').filter(context.params, function(err,q) {
if (err) { return callback(err); }
q.take(10, function(err, result) {
if (err) { return callback(err); }
callback(null, result);
});
});
*/
DataModel.prototype.filter = function(params, callback) {
if (typeof callback === 'function') {
return filterInternal.bind(this)(params, callback);
}
else {
return Q.nbind(filterInternal, this)(params);
}
};
/**
* Prepares a data query with the given object as parameters and returns the equivalent DataQueryable instance
* @param {*} obj - An object which represents the query parameters
* @returns DataQueryable - An instance of DataQueryable class that represents a data query based on the given parameters.
* @example
context.model('Order').find({ "paymentMethod":1 }).orderBy('dateCreated').take(10, function(err,result) {
if (err) { return callback(err); }
return callback(null, result);
});
*/
DataModel.prototype.find = function(obj) {
var self = this, result;
if (_.isNil(obj))
{
result = new DataQueryable(this);
result.where(self.primaryKey).equal(null);
return result;
}
var find = { }, findSet = false;
if (_.isObject(obj)) {
if (obj.hasOwnProperty(self.primaryKey)) {
find[self.primaryKey] = obj[self.primaryKey];
findSet = true;
}
else {
//get unique constraint
var constraint = _.find(self.constraints, function(x) {
return x.type === 'unique';
});
//find by constraint
if (_.isObject(constraint) && _.isArray(constraint.fields)) {
//search for all constrained fields
var findAttrs = {}, constrained = true;
_.forEach(constraint.fields, function(x) {
if (obj.hasOwnProperty(x)) {
findAttrs[x] = obj[x];
}
else {
constrained = false;
}
});
if (constrained) {
_.assign(find, findAttrs);
findSet = true;
}
}
}
}
else {
find[self.primaryKey] = obj;
findSet = true;
}
if (!findSet) {
_.forEach(self.attributeNames, function(x) {
if (obj.hasOwnProperty(x)) {
find[x] = obj[x];
}
});
}
result = new DataQueryable(this);
findSet = false;
//enumerate properties and build query
for(var key in find) {
if (find.hasOwnProperty(key)) {
if (!findSet) {
result.where(key).equal(find[key]);
findSet = true;
}
else
result.and(key).equal(find[key]);
}
}
if (!findSet) {
//there is no query defined a dummy one (e.g. primary key is null)
result.where(self.primaryKey).equal(null);
}
return result;
};
/**
* Selects the given attribute or attributes and return an instance of DataQueryable class
* @param {...string} attr - An array of fields, a field or a view name
* @returns {DataQueryable}
*/
DataModel.prototype.select = function(attr) {
var result = new DataQueryable(this);
return result.select.apply(result, arguments);
};
/**
* Prepares an ascending order by expression and returns an instance of DataQueryable class.
* @param {string|*} attr - A string that is going to be used in this expression.
* @returns DataQueryable
* @example
context.model('Person').orderBy('givenName').list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataModel.prototype.orderBy = function(attr) {
var result = new DataQueryable(this);
return result.orderBy(attr);
};
/**
* Takes an array of maximum [n] items.
* @param {Number} n - The maximum number of items that is going to be retrieved
* @param {Function=} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain the result.
* @returns DataQueryable|undefined If callback parameter is missing then returns a DataQueryable object.
*/
DataModel.prototype.take = function(n, callback) {
n = n || 25;
var result = new DataQueryable(this);
if (typeof callback === 'undefined')
return result.take(n);
result.take(n, callback);
};
/**
* Returns an instance of DataResultSet of the current model.
* @param {Function=} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain the result.
* @returns {Promise<T>|*} If callback parameter is missing then returns a Promise object.
* @deprecated Use DataModel.asQueryable().list().
* @example
context.model('User').list(function(err, result) {
if (err) { return done(err); }
return done(null, result);
});
*/
DataModel.prototype.list = function(callback) {
var result = new DataQueryable(this);
return result.list(callback);
};
/**
* @returns {Promise|*}
*/
DataModel.prototype.getList = function() {
var result = new DataQueryable(this);
return result.list();
};
/**
* Returns the first item of the current model.
* @param {Function=} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain the result.
* @returns {Promise<T>|*} If callback parameter is missing then returns a Promise object.
* @deprecated Use DataModel.asQueryable().first().
* @example
context.model('User').first(function(err, result) {
if (err) { return done(err); }
return done(null, result);
});
*/
DataModel.prototype.first = function(callback) {
var result = new DataQueryable(this);
return result.select(this.attributeNames).first(callback);
};
/**
* A helper function for getting an object based on the given primary key value
* @param {String|*} key - The primary key value to search for.
* @param {Function} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain the result, if any.
* @returns {Deferred|*} If callback parameter is missing then returns a Deferred object.
* @example
context.model('User').get(1).then(function(result) {
return done(null, result);
}).catch(function(err) {
return done(err);
});
*/
DataModel.prototype.get = function(key, callback) {
var result = new DataQueryable(this);
return result.where(this.primaryKey).equal(key).first(callback);
};
/**
* Returns the last item of the current model based.
* @param {Function=} callback - A callback function where the first argument will contain the Error object if an error occured, or null otherwise. The second argument will contain the result.
* @returns {Promise<T>|*} If callback parameter is missing then returns a Promise object.
* @example
context.model('User').last(function(err, result) {
if (err) { return done(err); }
return done(null, result);
});
*/
DataModel.prototype.last = function(callback) {
var result = new DataQueryable(this);