-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathext.js
667 lines (520 loc) · 18.9 KB
/
ext.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
import Ember from 'ember';
import { assert, warn } from "ember-data/-private/debug";
import {
typeForRelationshipMeta,
relationshipFromMeta
} from "ember-data/-private/system/relationship-meta";
import Model from "ember-data/model";
import EmptyObject from "ember-data/-private/system/empty-object";
var get = Ember.get;
var Map = Ember.Map;
var MapWithDefault = Ember.MapWithDefault;
var relationshipsDescriptor = Ember.computed(function() {
if (Ember.testing === true && relationshipsDescriptor._cacheable === true) {
relationshipsDescriptor._cacheable = false;
}
var map = new MapWithDefault({
defaultValue() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty((name, meta) => {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get(typeForRelationshipMeta(meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).readOnly();
var relatedTypesDescriptor = Ember.computed(function() {
if (Ember.testing === true && relatedTypesDescriptor._cacheable === true) {
relatedTypesDescriptor._cacheable = false;
}
var modelName;
var types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
meta.key = name;
modelName = typeForRelationshipMeta(meta);
assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", modelName);
if (!types.contains(modelName)) {
assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!modelName);
types.push(modelName);
}
}
});
return types;
}).readOnly();
var relationshipsByNameDescriptor = Ember.computed(function() {
if (Ember.testing === true && relationshipsByNameDescriptor._cacheable === true) {
relationshipsByNameDescriptor._cacheable = false;
}
var map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
meta.key = name;
var relationship = relationshipFromMeta(meta);
relationship.type = typeForRelationshipMeta(meta);
map.set(name, relationship);
}
});
return map;
}).readOnly();
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
Model.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@param {store} store an instance of DS.Store
@return {DS.Model} the type of the relationship, or undefined
*/
typeForRelationship(name, store) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: Ember.computed(function() {
return new EmptyObject();
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
```
```app/models/message.js
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
```
App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' }
App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' }
@method inverseFor
@static
@param {String} name the name of the relationship
@return {Object} the inverse relationship, or null
*/
inverseFor(name, store) {
var inverseMap = get(this, 'inverseMap');
if (inverseMap[name]) {
return inverseMap[name];
} else {
var inverse = this._findInverseFor(name, store);
inverseMap[name] = inverse;
return inverse;
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor(name, store) {
var inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
var propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })`
var options = propertyMeta.options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind, inverse;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName);
assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName +
"' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse));
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
if (propertyMeta.type === propertyMeta.parentType.modelName) {
warn(`Detected a reflexive relationship by the name of '${name}' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.`, false, {
id: 'ds.model.reflexive-relationship-without-inverse'
});
}
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
var filteredRelationships = possibleRelationships.filter((possibleRelationship) => {
var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " +
inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
filteredRelationships.length < 2);
if (filteredRelationships.length === 1 ) {
possibleRelationships = filteredRelationships;
}
assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " +
this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, relationshipsSoFar) {
var possibleRelationships = relationshipsSoFar || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return possibleRelationships; }
var relationships = relationshipMap.get(type.modelName);
relationships = relationships.filter((relationship) => {
var optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationships = Ember.get(Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
var fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
get(this, 'relationshipsByName').forEach((relationship, name) => {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType(callback, binding) {
let relationshipTypes = get(this, 'relatedTypes');
for (let i = 0; i < relationshipTypes.length; i++) {
let type = relationshipTypes[i];
callback.call(binding, type);
}
},
determineRelationshipType(knownSide, store) {
let knownKey = knownSide.key;
let knownKind = knownSide.kind;
let inverse = this.inverseFor(knownKey, store);
let key, otherKind;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
}
});
Model.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">DS.Model</span> the type of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
var serializedHasManyName = name.toUpperCase() + '_IDS';
json[serializedHasManyName] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor(name) {
return get(this.constructor, 'relationshipsByName').get(name);
},
inverseFor(key) {
return this.constructor.inverseFor(key, this.store);
}
});