-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-activerecord.js
848 lines (793 loc) · 24.8 KB
/
angular-activerecord.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
/**
* @licence ActiveRecord for AngularJS
* (c) 2013-2014 Bob Fanger, Jeremy Ashkenas, DocumentCloud
* License: MIT
*/
angular.module('ActiveRecord', []).factory('ActiveRecord', ['$http', '$q', '$parse', '$injector', function($http, $q, $parse, $injector) {
'use strict';
/**
* If the value of the named property is a function then invoke it; otherwise, return it.
* @param {Object} object
* @param {String} property
* @ignore
*/
var _result = function (object, property) {
if (object == null) return null;
var value = object[property];
return angular.isFunction(value) ? value.call(object) : value;
};
var _ucfirst = function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
var _lcfirst = function(string) {
return string.charAt(0).toLowerCase() + string.slice(1);
};
/**
* Apply the filters to the properties.
*
* @param {Object|null} filters The $readFilters or $writeFilters.
* @param {Object} properties
* @ignore
*/
var applyFilters = function (filters, properties) {
if (filters) {
angular.forEach(filters, function (filter, path) {
var expression = $parse(path);
var value = expression(properties);
if (angular.isDefined(value)) {
var newValue = (angular.isFunction(filter)) ? filter(value) : $parse(path + '|' + filter)(properties);
expression.assign(properties, newValue);
}
});
}
};
/**
* @class ActiveRecord ActiveRecord for AngularJS
* @constructor
* @param {Object} [properties] Initialize the record with these property values.
* @param {Object} [options]
*/
var ActiveRecord = function ActiveRecord(properties, options) {
this.$initialize.apply(this, arguments);
};
ActiveRecord.prototype = {
/**
* @property {String} $idAttribute The default name for the JSON id attribute is "id".
*/
$idAttribute: 'id',
/**
* @property {String} $urlRoot Used by $url to generate URLs based on the model id. "[urlRoot]/id"
*/
$urlRoot: null,
$nullValues: [null, undefined],
$emptyValues: function() { return [""].concat(this.$nullValues); },
/**
* Constructor logic
* (which is called by the autogenerated constructor via ActiveRecord.extend)
* @param {Object} [properties] Initialize the record with these property values.
* @param {Object} [options]
*/
$initialize: function (properties, options) {
options = options || {};
var defaults = _result(this, '$defaults');
if (defaults) {
angular.extend(this, defaults);
}
if (properties) {
if (options.parse) {
properties = this.$parse(properties);
}
if (options.readFilters) {
applyFilters(_result(this, '$readFilters'), properties);
}
angular.extend(this, properties);
this.$previousAttributes = function () {
return properties;
};
}
if (options.url) {
this.$url = options.url;
}
if (options.urlRoot) {
this.$urlRoot = options.urlRoot;
}
},
$hasAttributes: function(attrs) {
var model = this;
var isValid = true;
angular.forEach(attrs, function(v, k) {
if (model[k] !== v && !angular.isFunction(v)) {
isValid = false;
}
});
return isValid;
},
$getAttributes: function () {
var model = this;
var object = {};
angular.forEach(model.$attributes, function(v) {
object[v] = model[v];
});
return object;
},
/**
* Determine if the model has changed since the last sync (fetch/load).
*
* @param {String} [property] Determine if that specific property has changed.
* @returns {Boolean}
*/
$hasChanged: function (property) {
var changed = this.$changedAttributes();
if (property) {
return property in changed;
}
for (var i in changed) {
return true;
}
return false;
},
$attributeInAssociation: function(attr) {
var inAssoc = false;
attr = attr.toLowerCase();
angular.forEach(this.$associations, function(assoc, key) {
key = key.toLowerCase();
if (attr == key || (assoc.options.through && assoc.options.through.toLowerCase() == key)) inAssoc = true;
});
return inAssoc;
},
/**
* Return an object containing all the properties that have changed.
* Removed properties will be set to undefined.
*
* @param {Object} [diff] An object to diff against, determining if there would be a change.
* @returns {Object}
*/
$changedAttributes: function (diff) {
var current = diff || this; // By default diff against the current values
var changed = {};
var previousAttributes = this.$previousAttributes();
if (!diff) { // Skip removed properties (only compare the properties in the diff object)
for (var property in previousAttributes) {
if (typeof current[property] === 'undefined') {
changed[property] = current[property];
}
}
}
for (var property in current) {
if (current.hasOwnProperty(property) && property.indexOf("$") !== 0 && !this.$attributeInAssociation(property)) {
var value = current[property];
if (typeof value !== 'function' && angular.equals(value, previousAttributes[property]) === false && (!this.$attributes || this.$attributes.indexOf(property) !== -1)) {
changed[property] = value;
}
}
}
return changed;
},
/**
* Get the previous value of a property.
* @param {String} [property]
*/
$previous: function (property) {
var previousAttributes = this.$previousAttributes();
if (property == null || !previousAttributes) {
return null;
}
return previousAttributes[property];
},
/**
* Get all of the properties of the model at the time of the previous sync (fetch/save).
* @returns {Object}
*/
$previousAttributes: function () {
return {};
},
$toCamelCase: function(string) {
var camelCase = string.replace (/(?:^|[-_])(\w)/g, function (_, c) {
return c ? c.toUpperCase () : '';
});
return camelCase;
},
$computeData: function(data) {
data = data || this;
var model = this;
angular.forEach(data, function(value, key) {
var camelCaseKey = model.$toCamelCase(key);
var lowerCaseKey = camelCaseKey.toLowerCase();
var assocName = null;
var module = null;
angular.forEach(model.$associations, function(valueAssoc, keyAssoc) {
var Assoc = $injector.get(keyAssoc);
if (lowerCaseKey == keyAssoc.toLowerCase()) {
assocName = keyAssoc;
} else if (lowerCaseKey == Assoc.prototype.$plural.toLowerCase()) {
assocName = Assoc.prototype.$plural;
module = keyAssoc;
} else if (valueAssoc.options.through) {
var Related = $injector.get(valueAssoc.options.through);
var relName = Related.prototype.$plural || Related.prototype.$name || valueAssoc.options.through;
if (lowerCaseKey == relName.toLowerCase()) {
module = valueAssoc.options.through;
assocName = relName;
}
}
});
if (assocName) {
if (!module) module = assocName;
var lowerCamelCaseKey = _lcfirst(assocName);
model[lowerCamelCaseKey] = [];
var AssocModel = $injector.get(module);
if (angular.isArray(value)) {
angular.forEach(value, function(v) {
var assocModel = new AssocModel();
assocModel.$computeData(v);
model[lowerCamelCaseKey].push(assocModel);
});
} else {
var assocModel = new AssocModel();
assocModel.$computeData(value);
model[lowerCamelCaseKey] = assocModel;
}
} else {
model[key] = value;
}
});
data = angular.copy(model);
model.$previousAttributes = function () {
return data;
};
return model;
},
/**
* (re)load data from the backend.
* @param {Object} [options] sync options
* @return $q.promise
*/
$fetch: function (options) {
var model = this;
var deferred = $q.defer();
this.$sync('read', this, options).then(function (response) {
var data = model.$parse(response.data, options);
if (angular.isObject(data)) {
applyFilters(_result(model, '$readFilters'), data);
model.$computeData(data);
model.$validate();
data = angular.copy(model);
model.$previousAttributes = function () {
return data;
};
deferred.resolve(model);
} else {
deferred.reject('Not a valid response type');
}
}, deferred.reject);
return deferred.promise;
},
$validationErrorMessages: {},
$validations: {},
$fieldTranslations: {},
$errors: {},
$isValid: function(fieldName) {
var valid = false;
if (Object.keys(this.$errors).length === 0) {
valid = true;
} else if (fieldName && !this.$errors[fieldName]) {
valid = true;
}
return valid;
},
$getErrorMessage: function(fieldName, functionName) {
var validationValue = this.$validations[fieldName][functionName];
var fieldValue = this[fieldName];
var errorMessage = this.$validationErrorMessages[functionName] || "is invalid";
if (angular.isFunction(errorMessage)) errorMessage = errorMessage(fieldName, fieldValue, validationValue);
if (typeof sprintf !== "undefined") {
errorMessage = sprintf(errorMessage, {fieldName: this.$fieldTranslations[fieldName] || fieldName, fieldValue: fieldValue, validationValue: validationValue});
}
return errorMessage;
},
$applyValidation: function(fieldName, fieldValue, errors) {
if (!errors) errors = [];
var mthis = this;
angular.forEach(this.$validations[fieldName], function(validationValue, functionName) {
if (functionName != "required" && functionName != "notEmpty" && mthis[functionName]) {
if (mthis[functionName](fieldValue, validationValue) !== true) {
errors.push(mthis.$getErrorMessage(fieldName, functionName));
}
}
});
return errors;
},
$validateOne: function(fieldName) {
var errors = [];
delete this.$errors[fieldName];
if (this.$validations[fieldName]) {
var mthis = this;
if (mthis.hasOwnProperty(fieldName)) {
var props = typeof mthis[fieldName] == "object" ? mthis[fieldName] : [mthis[fieldName]];
var notEmptyValidation = false;
if (mthis.$validations[fieldName].notEmpty) {
if (mthis.$validations[fieldName].notEmpty !== true && mthis.$validations[fieldName].notNull) {
notEmptyValidation = mthis.$validations[fieldName].notEmpty;
} else if (mthis.$validations[fieldName].notEmpty) {
notEmptyValidation = mthis.$emptyValues();
} else if (mthis.$validations[fieldName].notNull) {
notEmptyValidation = mthis.$emptyValues();
}
}
var emptyError = true;
angular.forEach(props, function(prop) {
if (notEmptyValidation === false || notEmptyValidation.indexOf(prop) === -1) {
emptyError = false;
errors = mthis.$applyValidation(fieldName, prop, errors);
}
});
if (emptyError) {
errors.push(mthis.$getErrorMessage(fieldName, "notEmpty"));
}
} else if (this.$validations[fieldName].required) {
var errMessage = null;
if (angular.isObject(this.$validations[fieldName].required) && this.$validations[fieldName].required.message) {
errMessage = this.$validations[fieldName].required.message;
} else if (this.$validationErrorMessages.required) {
errMessage = this.$validationErrorMessages.required;
} else {
errMessage = "is required";
}
if (angular.isFunction(errMessage)) errMessage = errMessage(fieldName);
errors.push(errMessage);
}
}
if (errors.length) {
this.$errors[fieldName] = errors;
}
return this.$isValid(fieldName);
},
$validate: function(fieldName) {
if (fieldName) return this.$validateOne(fieldName);
var mthis = this;
this.$errors = {};
angular.forEach(this.$validations, function(validation, validationKey) {
mthis.$validateOne(validationKey);
});
return this.$isValid();
},
$saveBelongsToAssociations: function(values, options, deferred) {
var model = this;
// we want to save associations before.. so we need some callback stuff
var nbrLeft = 0;
var nbrFound = 0;
var err = false;
var assocsaveCallbackContainer = function(assoc) {
return function() {
if (err) return;
if (assoc.$isNew()) {
err = true;
return deferred.reject();
}
nbrLeft--;
if (nbrLeft === 0) {
model.$save(values, options).then(function(model) {
deferred.resolve(model);
}).catch(function(err) {
deferred.reject(err);
});
}
};
};
// get all associations data and save them if needed
angular.forEach(this.$associations, function(assocObj, assocKey) {
var keyName = assocKey;
if (assocObj.options.singular) keyName = assocObj.options.singular;
keyName = _lcfirst(keyName);
var assoc = model["$" + keyName];
if (assoc && assocObj.type == "belongsTo") {
if (assoc.$isNew()) {
nbrFound++;
nbrLeft++;
assoc.$save().then(
assocsaveCallbackContainer(assoc)
).catch(function(error) {
err = true;
deferred.reject(error);
});
} else {
model[assocObj.options.key] = assoc[assoc.$idAttribute];
}
}
});
return nbrFound;
},
$saveHasManyAssociations: function(deferred) {
var model = this;
var nbrLeft = 0;
var nbrFound = 0;
var err = false;
var assocsaveCallbackContainer = function(assoc) {
return function() {
if (err) return;
if (assoc.$isNew()) {
err = true;
return deferred.reject();
}
nbrLeft--;
if (nbrLeft === 0) {
deferred.resolve(model);
}
};
};
angular.forEach(this.$associations, function(assocObj, assocKey) {
var Related = $injector.get(assocObj.options.through || assocKey);
var keyName = Related.prototype.$plural || Related.prototype.$name || assocObj.options.through;
keyName = _lcfirst(keyName);
var assocs = model[keyName];
if (assocs && assocObj.type == "hasMany") {
//delete assocs
var oldAssoc = model.$previousAttributes()[keyName];
if (oldAssoc && oldAssoc.length) {
var ids = [];
angular.forEach(assocs, function(obj) {
ids.push(obj[obj.$idAttribute]);
});
var url = model.$url() + (Related.prototype.$urlRessource || assocKey);
if (assocObj.options.batch) {
var elements = [];
angular.forEach(oldAssoc, function(obj) {
if (ids.indexOf(obj[obj.$idAttribute]) === -1) {
elements.push(obj);
}
});
if (elements.length) {
nbrFound++;
nbrLeft++;
Related.destroyAll(elements, {url: url}).then(
assocsaveCallbackContainer()
).catch(function(error) {
err = true;
callback(false, error);
});
}
} else {
angular.forEach(oldAssoc, function(obj) {
if (ids.indexOf(obj[obj.$idAttribute]) === -1) {
nbrFound++;
nbrLeft++;
obj.$destroy({url: url + "/" + obj[obj.$idAttribute]}).then(
assocsaveCallbackContainer(obj)
).catch(function(error) {
err = true;
callback(false, error);
});
}
});
}
}
angular.forEach(assocs, function(assoc) {
if (assoc.$isNew() || assoc.$hasChanged()) {
nbrFound++;
nbrLeft++;
assoc[assoc.$associations[model.$name].options.key] = model[model.$idAttribute];
assoc.$save().then(
assocsaveCallbackContainer(assoc)
).catch(function(error) {
err = true;
deferred.reject(error);
});
}
});
}
});
return nbrFound;
},
/**
* Save the record to the backend.
* @param {Object} [values] Set these values before saving the record.
* @param {Object} [options] sync options
* @return $q.promise
*/
$save: function (values, options) {
if (values) {
if (angular.isString(values)) {
values = {};
values[arguments[0]] = options;
options = arguments[2];
}
angular.extend(this, values);
}
var operation = this.$isNew() ? 'create' : 'update';
var model = this;
var deferred = $q.defer();
if (!model.$validate()) {
deferred.reject(model.$errors);
return deferred.promise;
}
options = options || {};
var filters = _result(this, '$writeFilters');
//if we have found some associations not already saved, we need to wait for our callback to be called
if (this.$saveBelongsToAssociations(values, options, deferred)) {
return deferred.promise;
}
var tdata = this.$isNew() ? this : this.$changedAttributes();
var data = {};
angular.forEach(tdata, function(v, k) {
if (!model.$attributeInAssociation(k)) {
data[k] = v;
}
});
if (filters) {
options.data = angular.copy(data);
applyFilters(filters, options.data);
} else {
options.data = angular.copy(data);
}
this.$sync(operation, this, options).then(function (response) {
var data = model.$parse(response.data, options);
if (angular.isObject(data)) {
applyFilters(_result(model, '$readFilters'), data);
angular.extend(model, data);
data = angular.copy(model);
model.$previousAttributes = function () {
return data;
};
}
if (!model.$saveHasManyAssociations(deferred)) deferred.resolve(model);
}).catch(function(err) {
deferred.reject(err);
});
return deferred.promise;
},
/**
* Destroy this model on the server if it was already persisted.
* @param {Object} [options] sync options
* @return $q.promise
*/
$destroy: function (options) {
var deferred = $q.defer();
if (this.$isNew()) {
deferred.resolve();
return deferred.promise;
}
this.$sync('delete', this, options).then(function () {
deferred.resolve();
}, deferred.reject);
return deferred.promise;
},
/**
* Generate the url for the $save, $fetch and $destroy methods.
* @return {String} url
*/
$url: function() {
var urlRoot = _result(this, '$urlRoot');
var urlRessource = _result(this, '$urlRessource');
if (urlRessource) urlRoot += urlRessource;
if (typeof this[this.$idAttribute] === 'undefined') {
return urlRoot;
}
if (urlRoot === null) {
throw 'Implement this.$url() or specify this.$urlRoot';
}
return urlRoot + (urlRoot.charAt(urlRoot.length - 1) === '/' ? '' : '/') + encodeURIComponent(this[this.$idAttribute]);
},
/**
* Process the data from the response and return the record-properties.
* @param {Object} data The data from the sync response.
* @param {Object} [options] sync options
* @return {Object}
*/
$parse: function (data, options) {
return data;
},
/**
* Process the record-properties and return the data for the resquest. (counterpart of $parse)
* Called automaticly by JSON.stringify: @link https://developer.mozilla.org/en-US/docs/JSON#toJSON()_method
*/
toJSON: function() {
return this;
},
/**
* @property {Object} $readFilters
* Preform post-processing on the properties after $parse() through angular filters.
* These could be done in $parse(), but $readFilters enables a more reusable and declarative way.
*/
$readFilters: null,
/**
* @property {Object} $writeFilters
* Preform pre-processing on the properties before $save() through angular filters.
* These could be done in toJSON(), but $readFilters enables a more reusable and declarative way.
*/
$writeFilters: null,
/**
* A model is new if it lacks an id.
*/
$isNew: function () {
return this[this.$idAttribute] == null;
},
/**
* By default calls ActiveRecord.sync
* Override to change the backend implementation on a per model bases.
* @param {String} operation "create", "read", "update" or "delete"
* @param {ActiveRecord} model
* @param {Object} options
* @return $q.promise
*/
$sync: function (operation, model, options) {
return ActiveRecord.sync.apply(this, arguments);
},
$associations: {}
};
/**
* Preform a CRUD operation on the backend.
*
* @static
* @param {String} operation "create", "read", "update" or "delete"
* @param {ActiveRecord} model
* @param {Object} options
* @return $q.promise
*/
ActiveRecord.sync = function (operation, model, options) {
if (typeof options === 'undefined') {
options = {};
}
if (!options.method) {
var crudMapping = {
create: 'POST',
read: 'GET',
update: 'PUT',
"delete": 'DELETE'
};
options.method = crudMapping[operation];
}
if (!options.url) {
options.url = _result(model, '$url');
}
if (options.filters) {
var extensions = [];
angular.forEach(options.filters, function(filter, key) {
if (angular.isArray(filter)) {
angular.forEach(filter, function(value) {
extensions.push(key + "[]=" + value);
});
} else {
extensions.push(key + "=" + filter);
}
});
options.url += "?" + extensions.join("&");
}
return $http(options);
};
ActiveRecord.lastId = 0;
/**
* Create a subclass.
* @static
* @param {Object} protoProps
* @param {Object} [staticProps]
* @return {Function} Constructor
*/
ActiveRecord.extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && typeof protoProps.$constructor === 'function') {
child = protoProps.$constructor;
} else {
child = function () {
this.$id = ++ActiveRecord.lastId;
return parent.apply(this, arguments);
};
}
angular.extend(child, parent, staticProps);
var Surrogate = function () { this.$constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps) {
angular.extend(child.prototype, protoProps);
}
child.__super__ = parent.prototype;
child.prototype.$associations = {};
return child;
};
ActiveRecord.hasMany = function(entity, options) {
if (!options) options = {};
if ($injector.has(entity) && (!options.through || $injector.has(options.through))) {
var mthis = this;
var Related = $injector.get(options.through || entity);
var isThrough = !!options.through;
var relatedName = _lcfirst(Related.prototype.$plural || Related.prototype.$name || options.through);
this.prototype.$associations[entity] = {type: "hasMany", options: options};
this.prototype["add" + entity] = function(model, relatedData) {
if (model.$isNew()) return "can't be new";
var options = this.$associations[entity].options;
if (!relatedData) relatedData = {};
var newEntity = null;
if (isThrough) {
newEntity = new Related(relatedData);
newEntity["add" + entity](model);
} else {
newEntity = model;
}
if (!this[relatedName]) this[relatedName] = [];
this[relatedName].push(newEntity);
return this;
};
}
};
ActiveRecord.belongsTo = function(entity, options) {
if (!options) options = {};
if ($injector.has(entity)) {
var name = _lcfirst(entity);
this.prototype.$associations[entity] = {type: "belongsTo", options: options};
this.prototype["add" + entity] = function(model) {
if (model.$isNew()) return "can't be new";
var relatedKey = this.$associations[entity].options.key;
this[name] = model;
this[relatedKey] = model[model.$idAttribute];
return model;
};
}
};
/**
* Load a single record.
*
* @static
* @param {Mixed} id
* @param {Object} [options]
* @return $q.promise
*/
ActiveRecord.fetchOne = function (id, options) {
var model = new this();
model[model.$idAttribute] = id;
return model.$fetch(options);
};
ActiveRecord.destroyAll = function(models, options) {
if (typeof options === 'undefined') {
options = {};
}
options.filters = {ids: []};
angular.forEach(models, function(model) {
if (model[model.$idAttribute]) options.filters.ids.push(model[model.$idAttribute]);
});
options.method = 'DELETE';
if (!options.url) options.url = _result(this.prototype, '$url');
return ActiveRecord.sync(null, null, options);
};
/**
* Load a collection of records.
*
* @static
* @param {Object} [options]
* @return $q.promise
*/
ActiveRecord.fetchAll = function (options) {
var ModelType = this;
var model = new ModelType();
var deferred = $q.defer();
model.$sync('read', model, options).then(function (response) {
var data = model.$parse(response.data, options);
if (angular.isArray(data)) {
var models = [];
var filters = ModelType.prototype.$readFilters;
angular.forEach(data, function (item) {
applyFilters(filters, item);
var newModel = new ModelType();
newModel.$computeData(item);
newModel.$validate();
models.push(newModel);
});
deferred.resolve(models);
} else if(data && data.meta && ( data.meta.count || data.meta.count == 0) && !isNaN(data.meta.count) && data.data && angular.isArray(data.data)) {
// This code has been added to allow for paginated results with a total count
var models = [];
var filters = ModelType.prototype.$readFilters;
angular.forEach(data.data, function (item) {
applyFilters(filters, item);
var newModel = new ModelType();
newModel.$computeData(item);
models.push(newModel);
});
deferred.resolve({count: data.meta.count, models: models});
} else {
deferred.reject('Not a valid response, expecting an array');
}
}, deferred.reject);
return deferred.promise;
};
return ActiveRecord;
}]);