-
Notifications
You must be signed in to change notification settings - Fork 7
/
backbone-schema.js
2018 lines (1754 loc) · 74.5 KB
/
backbone-schema.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
/**
* Backbone-schema.js 0.1.0
* (c) 2012 Marcus Mac Innes, Redpie
*
* Backbone-schema may be freely distributed under the MIT license
* For details and documentation: https://github.com/redpie/backbone-schema
* Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone
*/
(function(moduleFactory) {
if(typeof exports === 'object') {
module.exports = moduleFactory(require('underscore'), require('backbone'));
} else if(typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], moduleFactory);
} else {
window.Backbone.Schema = moduleFactory(window._, window.Backbone);
}
}(function(_, Backbone, undefined) {
var Schema = {};
function log() {}
function toObject(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
function typeOf(Value, aType) {
return(_.isFunction(Value) && _.isFunction(aType)) ? (new Value()) instanceof aType : false;
}
function instanceOf(instance, aType) {
return _.isFunction(aType) ? instance instanceof aType : false;
}
// Replace default backbone inheritance code with the following which
// returns the value returned by the underlying constructors which
// facilitates the IdentityMap feature
var Ctor = function() {};
function inherits(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if(protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function() {
// Returning the return value from parent below facilitates
// the IdentityMap feature
return parent.apply(this, arguments);
};
}
// Inherit class (static) properties from parent.
_.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
Ctor.prototype = parent.prototype;
child.prototype = new Ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if(protoProps) {
_.extend(child.prototype, protoProps);
}
// Add static properties to the constructor function, if supplied.
if(staticProps) {
_.extend(child, staticProps);
}
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child['__super__'] = parent.prototype;
return child;
}
function extend(protoProps, staticProps) {
var child = inherits(this, protoProps, staticProps);
child.extend = this.extend;
child.prototype.uniqueTypeId = _.uniqueId();
return child;
}
/**
* JSONPointer implementation of http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-03
* @param {Object} obj JSON object
* @constructor
*/
function JSONPointer(obj) {
this.obj = obj;
}
JSONPointer.prototype = {
/**
* Gets the value located at the JSONPointer path
* @param {String} path Path in the format "/foo/bar/0"
* @return {Number|String|Object} Value located at path
*/
get: function(path) {
if(path === '') {
return this.obj;
}
return this._find(this.obj, this._toParts(path));
},
/**
* Sets the proerty located at the provided path
* @param {[type]} path Path in the format "/foo/bar/0"
* @param {[type]} value Value to set
*/
set: function(path, value) {
if(path === '') {
this.obj = value;
return true;
}
var parts = this._toParts(path),
name = parts.pop(),
property = parts.length > 0 ? this._find(this.obj, parts) : this.obj;
if(property !== undefined && property !== null) {
property[name] = value;
return true;
}
return false;
},
/**
* @private
*/
_toParts: function(path) {
return _.map(path.split('/').slice(1), function(part) {
return part.replace('~1', '/').replace('~0', '~');
});
},
/**
* @private
*/
_find: function(obj, paths) {
var property = obj[paths[0]];
if(property !== undefined && property !== null && paths.length > 1) {
paths.shift();
return this._find(property, paths);
}
return property;
}
};
JSONPointer.isPointer = function(pointer) {
return(pointer !== undefined && pointer !== null) || pointer.indexOf('#') >= 0 ? true : false;
};
JSONPointer.fragmentPart = function(path) {
var parts = path.split('#');
return parts.length > 1 ? parts[1] : undefined;
};
JSONPointer.removeFragment = function(path) {
return path.split('#')[0];
};
/**
* SchemaFactory provides methods to register and create new Models and Collections
* from JSON Schemas.
* @constructor
*/
var SchemaFactory = Schema.Factory = function SchemaFactory(options) {
// Initialise the options object
options = options || {};
this.options = options;
/**
* Maintains a list of registered schemas, indexed by schema.id
* @type {Object}
*/
this.registeredSchemas = {};
/**
* Maintains a list of registered models, indexed by schema.id
* @type {Object}
*/
this.registeredSchemaTypes = {};
/**
* Maintains a list of parsed schemas, indexed by schema.id
* @type {Object}
*/
this.parsedSchemaCache = {};
/**
* Maintains a list of constructed Models and Collections, indexed by schema.id
* @type {Object}
*/
this.typeCache = {};
/**
* Maintains a list of all instantiated models
* @type {Object}
* @private
*/
this.instanceCache = {};
// Ensure the base model is of type SchemaModel
if(options.model && !(typeOf(options.model, SchemaModel))) {
throw new Error("options.model MUST extend Backbone.Schema.Model");
}
// Ensure the base model is of type SchemaCollection
if(options.collection && !(typeOf(options.collection, SchemaCollection))) {
throw new Error("options.collection MUST extend Backbone.Schema.Collection");
}
// Ensure the base model is of type SchemaValueCollection
if(options.valueCollection && !(typeOf(options.valueCollection, SchemaValueCollection))) {
throw new Error("options.valueCollection MUST extend Backbone.Schema.ValueCollection");
}
// All models created by this factory will be of the provided type or SchemaModel
this.baseModel = options.model || SchemaModel;
// All collections created by this factory will be of the provided type or SchemaCollection
this.baseCollection = options.collection || SchemaCollection;
// All value collections created by this factory will be of the provided type or SchemaValueCollection
this.baseValueCollection = options.valueCollection || SchemaValueCollection;
};
SchemaFactory.prototype = {
/**
* Registers the provided schema and optional model.
* This method allows you to associate a Model or Collection with a
* particular schema which is useful when you wish to provide custom
* functionality for schemas which may be embedded in other schemas.
* @param {String|Object} schema Provide a schema id or a schema object
* @param {Backbone.Schema.Model|Backbone.Schema.Collection|Backbone.Schema.ValueCollection} model Provide a model or collection to associate with this schema
* @return {this}
*/
register: function(schema, model) {
var schemaId;
if(_.isString(schema)) {
schemaId = schema;
} else {
schemaId = schema.id;
}
if(schemaId === undefined || schemaId === null || schemaId === '') {
throw new Error('Cannot register a schema with no id');
}
if(_.isObject(schema)) {
this.registeredSchemas[schemaId] = schema;
delete this.parsedSchemaCache[schemaId];
}
if(model) {
this.registeredSchemaTypes[schemaId] = model;
delete this.typeCache[schemaId];
}
},
/**
* Unregister a schema
* @param {String} schemaId The schema id of the schema you wish to unregister
* @return {this}
*/
unregister: function(schemaId) {
delete this.registeredSchemas[schemaId];
delete this.registeredSchemaTypes[schemaId];
delete this.parsedSchemaCache[schemaId];
delete this.typeCache[schemaId];
return this;
},
/**
* Clears all caches. Used by the tests
* @return {this}
*/
reset: function() {
this.registeredSchemas = {};
this.registeredSchemaTypes = {};
this.parsedSchemaCache = {};
this.typeCache = {};
this.instanceCache = {};
return this;
},
/**
* Create a Model or Collection from the provided schema
* @param {String|Object} schema Provide the schema or the schema id of a previously refistered schema
* @param {Object=} model Provides an optional model or collection which overrides the default base class.
* @return {Object} Returns the contructed model or collection
*/
create: function(schema, model) {
if(_.isString(schema)) {
schema = this._get(schema);
} else if(schema.id) {
this.register(schema, model);
}
schema = this.parse(schema);
if(schema.type && schema.type === 'array') {
return this._createCollection(schema, undefined, model);
}
return this._createModel(schema, undefined, model);
},
/**
* Create an instance of a Model or Collection from the provided schema
* @param {String|Object} schema Provide the schema or the schema id of a previously refistered schema
* @param {Object=} model Provides an optional model or collection which overrides the default base class.
* @param {Object=} attributes [description]
* @param {Object=} options [description]
* @return {[type]} Returns an instance of model or collection
*/
createInstance: function(schema, model, attributes, options) {
if(!_.isFunction(model) && options === undefined) {
options = attributes;
attributes = model;
model = undefined;
}
var Model = this.create(schema, model);
return new Model(attributes, options);
},
/**
* @private
*/
_get: function(schemaId) {
if(schemaId === undefined) {
return undefined;
}
schemaId = schemaId.split('#')[0];
var schema = this.registeredSchemas[schemaId];
if(schema === undefined) {
schema = this.fetch(schemaId);
if(schema !== undefined) {
this.registeredSchemas[schemaId] = schema;
} else {
throw new Error('Cannot find schema ' + schemaId ? schemaId : '');
}
}
return schema;
},
/**
* Override this method to provide a way to fetch schema from a server
* @return {Object|undefined} Returns the schema or undefined if not found
*/
fetch: function(schemaId) {
return undefined;
},
/**
* Creates an object model representation of schema by populating
* all references and extensions ($ref's) which their corresponding
* schemas in full.
* @param {Object} schema Provide the schema to parse
* @return {Object} Returns the parsed schema
*/
parse: function(schema) {
// Ensure that root schemas are identifiable by an id.
// This is used for caching purposes internally
if(schema.id === undefined || schema.id === null) {
schema.id = JSON.stringify(schema);
}
return this._parse(schema, schema);
},
/**
* Removed the trailing # from a schema id
* @param {String} schemaId Schema id
* @return {String} Schema id minus the trailing #
* @private
*/
_removeTrailingHash: function(schemaId) {
// Remove trailing #
return schemaId !== undefined && schemaId.length > 1 ? (schemaId.charAt(schemaId.length - 1) === '#' ? schemaId.slice(0, -1) : schemaId) : undefined;
},
/**
* Provides the recursive parse method
* @param {Object} schema Provide the schema to parse
* @param {Object} rootSchema Provide the root schema which corresponds to $ref="#"
* @return {Object} Returns the parsed schema
* @private
*/
_parse: function(schema, rootSchema) {
if(schema === undefined || schema === null) {
return undefined;
}
var schemaId = this._removeTrailingHash(schema.id);
if(schemaId && this.parsedSchemaCache[schemaId]) {
return this.parsedSchemaCache[schemaId];
}
var reference = schema['$ref'];
if(reference && this.parsedSchemaCache[reference]) {
return this.parsedSchemaCache[reference];
}
///////////////
// To avoid infinite loops on circular schema references, define the
// expanded schema now (ahead of evaluating it) and add it to the cache.
// Re-entrant calls will pull the empty object from the cache which
// will eventually be populated as the recursions exit.
//var expandedSchema = schema;
if(schemaId !== undefined) {
this.parsedSchemaCache[schemaId] = schema;
}
///////////////
// Process references early, as they can't have any other
// fields/properties present.
if(reference) {
// Short circuit most common usage
if(reference === '#') {
return rootSchema;
}
var parts = reference.split('#'),
referencedSchemaId = parts[0],
referencedFragment = parts.length > 1 ? parts[1] : '',
referencedSchema;
if(referencedSchemaId === '') {
referencedSchema = rootSchema;
} else {
var fetchedSchema = this._get(referencedSchemaId);
referencedSchema = this._parse(fetchedSchema, fetchedSchema);
}
var toReturn = referencedFragment.length > 0 ? new JSONPointer(referencedSchema).get(referencedFragment) : referencedSchema;
// Ensure referenced fragment has an id
if(toReturn && (toReturn.id === undefined || toReturn.id === null)) {
toReturn.id = reference.charAt(0) === '#' ? referencedSchema.id + reference : reference;
}
return toReturn;
}
//////////////
// Process child properties first so that object graph completes
// leaf nodes first
var properties = schema.properties;
if(properties) {
_.each(properties, function(property, key) {
properties[key] = this._parse(property, rootSchema);
}, this);
}
//////////////
// TODO: "not" below is a strange one and needs thinking through
_.each(['items', 'anyOf', 'allOf', 'not'], function(propertyName) {
var items = schema[propertyName];
if(items) {
if(_.isArray(items)) {
for(var i = 0, l = items.length; i < l; i++) {
schema[propertyName][i] = this._parse(items[i], rootSchema);
}
} else {
schema[propertyName] = this._parse(items, rootSchema);
}
}
}, this);
var extensions = schema['extends'];
if(extensions) {
// Remove the extends attribute as we are going to perform the extension below
schema['extends'] = undefined;
_.each(_.isArray(extensions) ? extensions : [extensions], function(extension) {
var expandedExtension = this._parse(extension, rootSchema);
extendSchema(schema, expandedExtension);
}, this);
}
return schema;
},
/**
* Creates a SchemaModel from the provided Schema
* @param {Object} schema Provide the schema with which to build the model
* @param {Object=} options Provide any options
* @param {Object=} baseModel Provide a base model used to override the default
* @return {Object} Return a Schema Model
* @private
*/
_createModel: function(schema, options, baseModel) {
var schemaId = schema.id;
// Attempt to re-use previously constructed models
if(schemaId && this.typeCache[schemaId]) {
return this.typeCache[schemaId];
}
// Create a meaningful name for the mode using the schema.title (whitespace removed)
var modelName = schema.title ? schema.title.replace(/[^\w]/gi, '') : 'Unknown';
// Add SchemaModel on the end to create "{Title}SchemaModel"
var typeName = modelName + 'SchemaModel';
log('Create Custom Schema Model Type: ' + typeName);
// Determine the base model starting with the baseModel passed in above,
// next try the a model regsitered against the schemaId and
// lastly try the SchemaFactory default baseModel
var BaseModel = baseModel || (schemaId && this.registeredSchemaTypes[schemaId]) || this.baseModel;
// Ensure the base model is of type "SchemaModel"
if(!BaseModel.isSchemaModel) {
throw new Error('Base model for schema ' + schemaId + ' is not a SchemaModel');
}
// Eval the constructor code as we want to inject the typeName which will allow models
// created with this type to have meaningful names when debugging
// Construct the new model
var model = BaseModel.extend({
constructor: function(attributes, options) {
var toReturn = BaseModel.prototype.constructor.apply(this, arguments);
if(toReturn) {
return toReturn;
}
if(!options || options.validation !== false) {
this.validation = new ValidationModel(this.schema.properties ? _.keys(this.schema.properties) : ['value']);
}
},
factory: this,
// Save a reference to this factory for future use
schema: schema,
typeName: typeName
}, {
// Make the schema and typeName also available as static properties of the type
schema: schema,
typeName: typeName
});
// Only cache the resulting model if a we have a schema id.
if(schemaId) {
this.typeCache[schemaId] = model;
}
var defaults = {},
schemaRelations = {};
// Using the schema.properties definitions determine if there
// are any relations and if so create corresponding models or collections
if(schema.properties) {
_.each(schema.properties, function(property, key) {
// Extract any default values from schema and assign to model's default object
// Array access is required as 'default' is a reserved word.
if(property['default'] !== undefined) {
defaults[key] = property['default'];
}
// Only types "object" and "array" map to relations
switch(property.type) {
case 'object':
// Found a HasOne relation, so create a corresponding model
schemaRelations[key] = this._createModel(property, options);
break;
case 'array':
// Found a HasMany relation, so create a corresponding collection
schemaRelations[key] = this._createCollection(property, options);
break;
default:
break;
}
}, this);
}
// Assign the resulting default and relations to the model's prototype
model.prototype.defaults = defaults;
model.prototype.schemaRelations = schemaRelations;
return model;
},
/**
* Creates a SchemaCollection from the provided Schema
* @param {Object} schema Provide the schema with which to build the model
* @param {Object=} options Provide any options
* @param {Object=} baseCollection Provide a base collection used to override the default
* @return {Object} Return a Schema Collection
* @private
*/
_createCollection: function(schema, options, baseCollection) {
var schemaId = schema.id;
// Attempt to re-use previously constructed collections
if(schemaId && this.typeCache[schemaId] !== undefined) {
return this.typeCache[schemaId];
}
// Create a meaningful name for the mode using the schema.title (whitespace removed)
var collectionName = schema.title ? schema.title.replace(/[^\w]/gi, '') : 'Unknown',
items = schema.items,
model, typeName, BaseCollection;
// Depending on the items.type we need to create a different base collection
switch(items.type) {
// Create a model based collection for object types
case 'object':
// Create the model type from the items properties
model = this._createModel(items, options);
// Strip the word "Model" (5 letters) from the end of the model's schemaModelType
typeName = (schema.title ? collectionName : model.typeName.slice(0, -5)) + 'Collection';
// Determine the base collection starting with the baseCollection passed in above,
// next try the a collection regsitered against the schemaId and
// lastly try the SchemaFactory default baseCollection
BaseCollection = baseCollection || this.registeredSchemaTypes[schemaId] || this.baseCollection;
// Ensure the base collection is of type "SchemaCollection"
if(!BaseCollection.isSchemaCollection) {
throw new Error('Base collection for schema ' + schemaId + ' is not a SchemaCollection');
}
break;
// Create a value based collection for value types
case 'string':
case 'number':
case 'integer':
case 'boolean':
typeName = (schema.title ? collectionName : items.type.charAt(0).toUpperCase() + items.type.slice(1)) + 'Collection';
// Determine the base collection starting with the collection regsitered against the schemaId and
// lastly try the SchemaFactory default baseValueCollection
BaseCollection = this.registeredSchemaTypes[schemaId] || this.baseValueCollection;
// Ensure the base collection is of type "SchemaValueCollection"
if(!BaseCollection.isSchemaValueCollection) {
throw new Error('Base collection for schema ' + schemaId + ' is not a SchemaValueCollection');
}
break;
// These types are not currently supported
case 'array':
case 'any':
case 'null':
throw new Error('Unsupport items type:' + items.type);
default:
throw new Error('Unknown items type: ' + items.type);
}
log('Create Custom Schema Collection Type: ' + typeName);
// Construct the new collection
var collection = BaseCollection.extend({
constructor: function(models, options) {
var toReturn = BaseCollection.prototype.constructor.apply(this, arguments);
if(toReturn) {
return toReturn;
}
if(!options || options.validation !== false) {
this.validation = new ValidationErrorsCollection();
}
},
model: model,
schema: schema,
factory: this,
// Save a reference to this factory for future use
typeName: typeName,
validation: undefined,
initValidation: function() {
if(this.options.validate !== false) {
this.validation = new ValidationErrorsCollection();
}
},
newModel: function(attributes, options) {
options = options || {};
options.schema = options.schema || this.schema.items;
return new this.model(attributes, options);
},
addNewModel: function(attributes, options) {
var model = this.newModel(attributes, options);
this.add(model);
return model;
}
}, {
// Make the schema and typeName also available as static properties of the type
schema: schema,
typeName: typeName
});
// Only cache the resulting collection if a we have a schema id.
if(schemaId) {
this.typeCache[schemaId] = collection;
}
return collection;
}
};
/**
* Backbone.Schema.Model provides a schema aware Backbone.Model
* @constructor
* @extends Backbone.Model
*/
var SchemaModel = Schema.Model = Backbone.Model.extend({
/**
* JSON Schema associated with this model
* @type {Object}
*/
schema: {},
// Each time the Model is extended it will receive a new
// uniqueTypeId which can later be used to differentiate types
uniqueTypeId: _.uniqueId(),
/**
* Constructor function is used to provide named objects during debugging
*/
constructor: function SchemaModel(attributes, options) {
// IdentityMap using SchemaId
// TODO: (MMI) Bind to dispose event in order to remove the instance from
// the cache to avoid a memory leak
if(attributes && attributes[this.idAttribute]) {
var schemaId = this.schema ? this.schema.id : undefined;
if(schemaId) {
var cacheKey = attributes[this.idAttribute] + '|' + schemaId;
if(options === undefined || options.identityMap !== false) {
var cachedModel = this.factory.instanceCache[cacheKey];
if(cachedModel) {
return cachedModel;
}
}
this.factory.instanceCache[cacheKey] = this;
}
}
Backbone.Model.prototype.constructor.call(this, attributes, options);
},
/**
* Determines the server side url provided via schema links where model data can be located
* @return {String} Returns an API endpoint URL
*/
url: function() {
var schema = this.schema;
if(schema !== undefined && schema.links !== undefined) {
var url;
_.any(schema.links, function(link) {
if(link.rel !== undefined && link.rel === 'self') {
url = link.href;
return true; // break out of _.any
}
});
if(url !== undefined) {
// replace the url property on this method so that future calls
// don't need to re-process
return this.url = url.replace(/\{id\}/, encodeURIComponent(this.id));
}
}
return Backbone.Model.prototype.url.apply(this, arguments);
},
/**
* Overrides the default Backbone.Model.fetch behaviour and sets the default options.parse=true
* See https://github.com/documentcloud/backbone/issues/1843 for more details
* @param {Object=} options
* @return {Object} Returns a xhr object from the default fetch method
*/
fetch: function(options) {
options = options || {};
if(options.parse === void 0) {
options.parse = true;
}
return Backbone.Model.prototype.fetch.call(this, options);
},
/**
* Gets the value of a model attribute
* @param {String} key Provide the attribute name
* @return {String|Number|Object} Returns the attribute value
*/
get: function(key) {
// Check if the model has a property or method for the key
var value = this[key];
if(value !== undefined) {
return _.isFunction(value) ? value() : value;
}
var toReturn = Backbone.Model.prototype.get.apply(this, arguments);
// Lazy Initialisation of relations
// Check if the return value is an uninitialized relation
if(toReturn === undefined || toReturn === null) {
var RelationType = this.schemaRelations[key];
if(RelationType !== undefined) {
toReturn = this.attributes[key] = new RelationType(undefined, {
silent: true
});
}
}
return toReturn;
},
/**
* Sets the value of an attribute
* @param {String} key The attribute name
* @param {Number|String|Object} value The attribute value
* @param {Object=} options
*/
set: function(key, value, options) {
var attributes;
if(_.isObject(key) || key === undefined) {
attributes = key;
options = value;
} else {
attributes = {};
attributes[key] = value;
}
options = options || {};
if(options.validate === undefined) {
options.validate = false;
}
attributes = this._prepareAttributes(attributes, options);
return Backbone.Model.prototype.set.call(this, attributes, options);
},
/**
* Interates over the provided attributes and initializes any relations
* to their corresponding model or collection.
* @param {Object} attributes Attributes to initialize
* @param {Objects=} options
* @return {Object} Returns new initialized attributes
*/
_prepareAttributes: function(attributes, options) {
// TODO: If attributes are Models or Collections check the match the schema
if(attributes !== undefined && this.schema !== undefined && this.schemaRelations !== undefined) {
var attrs = {};
_.each(attributes, function(attribute, name) {
var Relation = this.schemaRelations[name];
if(Relation && !(attribute instanceof Backbone.Model || attribute instanceof Backbone.Collection)) {
attrs[name] = new Relation(attribute, _.extend({
silent: true
}, options));
} else {
attrs[name] = attribute;
}
}, this);
attributes = attrs;
}
return attributes;
},
/**
* Lock used to stop circular references from causing a stack overflow
* during toJSON serializtion
* @type {Boolean}
* @private
*/
toJSONInProgress: false,
/**
* Creates a serializable model
* @param {Object=} options
* @return {Object} Serializable model
*/
toJSON: function(options) {
if(this.toJSONInProgress) {
// This only happens when there is a circular reference
// and the model has already been serialized previously
return this.id ? toObject(this.idAttribute, this.id) : undefined;
}
this.toJSONInProgress = true;
var toReturn;
if(this.schema) {
_.each(this.schema.properties, function(property, name) {
var attribute = this.attributes[name];
if(attribute) {
var value;
if(this.schemaRelations[name]) {
value = attribute.toJSON(options);
} else {
value = attribute;
}
if(value !== undefined) {
if(toReturn === undefined) {
toReturn = {};
}
toReturn[name] = value;
}
}
}, this);
} else {
toReturn = Backbone.Model.prototype.toJSON.apply(this, arguments);
}
this.toJSONInProgress = false;
return toReturn;
},
/**
* Validates the model against the schema returning true if valid
* @param {Object} options Passed to the validate method
* @return {Boolean} Returns true if valid, otherwise false
*/
isValid: function(options) {
return this.validate(undefined, options) === undefined;
},
_validate: function(attributes, options) {
var toReturn = Backbone.Model.prototype._validate.apply(this, arguments);
if(options && options.validate === false) {
return true;
}
return toReturn;
},
/**
* Validates the model against the schema
* @param {Object=} options
* @return {Array} Returns an array of errors or undefined
*/
validate: function(attributes, options) {
if(!this.validation) {
return;
}
// If no attributes are supplied, then validate all schema properties
// by building an attributes array containing all properties.
if(attributes === undefined) {
attributes = {};
// Produce a list of all fields and their values.
_.each(this.schema.properties, function(value, key) {
attributes[key] = this.attributes[key];
}, this);
// Add any attributes that do not appear in schema
_.each(this.attributes, function(value, key) {
if (attributes[key] === undefined){
attributes[key] = this.attributes[key];
}
}, this);
}
// Dispose of previous validation models
_.each(this.validation.attributes, function(attribute, key) {
delete this.validation.attributes[key];
if(attribute.dispose) {
attribute.dispose();
}
}, this);
var errors = [];
_.each(attributes, function(value, key) {
log('Validating attribute: ' + key);
var attributeErrors = this.validateAttribute(key, value, options);
if(attributeErrors.length > 0) {
this.validation.set(key, new ValidationErrorsCollection(attributeErrors));
errors.push.apply(errors, attributeErrors);
}
}, this);
// Return nothing on success
if(errors.length > 0) {
log('Validation failed: ', errors);
return errors;
}
},
/**
* Validate an individual attribute
* @param {String} key [description]
* @param {Number|String|Object} value The value of the attribute
* @param {Object=} options
* @return {Array} Returns an array containing any validation errors
*/
validateAttribute: function(key, value, options) {
options = options || {};
// If a property is not defined in schema and additionalProperties is not set to false, then allow anything.
// Note: we don't currently support schema based additionalProperties, only boolean values
if(this.schema.additionalProperties !== false && (this.schema.properties === undefined || this.schema.properties[key] === undefined)) {
return [];
}
var schemaProperty = this.schema.properties[key],
errors = [];