forked from ember-data/active-model-adapter-dist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactive-model-adapter.js
705 lines (598 loc) · 20.6 KB
/
active-model-adapter.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
/*!
* @overview ActiveModelAdapter
* @copyright Copyright 2011-2015 Tilde Inc. and contributors
* Portions Copyright 2006-2011 Strobe Inc.
* Portions Copyright 2008-2011 Apple Inc. All rights reserved.
* @license Licensed under MIT license
* See https://raw.github.com/emberjs/ember.js/master/LICENSE
* @version 2.1.1
*/
(function() {
var loader, define, requireModule, require, requirejs;
var global = this;
(function() {
'use strict';
// Save off the original values of these globals, so we can restore them if someone asks us to
var oldGlobals = {
loader: loader,
define: define,
requireModule: requireModule,
require: require,
requirejs: requirejs
};
loader = {
noConflict: function(aliases) {
var oldName, newName;
for (oldName in aliases) {
if (aliases.hasOwnProperty(oldName)) {
if (oldGlobals.hasOwnProperty(oldName)) {
newName = aliases[oldName];
global[newName] = global[oldName];
global[oldName] = oldGlobals[oldName];
}
}
}
}
};
var _isArray;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var registry = {};
var seen = {};
var FAILED = false;
var LOADED = true;
var uuid = 0;
function unsupportedModule(length) {
throw new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `' +
length + '` arguments to define`');
}
var defaultDeps = ['require', 'exports', 'module'];
function Module(name, deps, callback) {
this.id = uuid++;
this.name = name;
this.deps = !deps.length && callback.length ? defaultDeps : deps;
this.module = { exports: {} };
this.callback = callback;
this.state = undefined;
this._require = undefined;
this.finalized = false;
this.hasExportsAsDep = false;
}
Module.prototype.makeDefaultExport = function() {
var exports = this.module.exports;
if (exports !== null &&
(typeof exports === 'object' || typeof exports === 'function') &&
exports['default'] === undefined) {
exports['default'] = exports;
}
};
Module.prototype.exports = function(reifiedDeps) {
if (this.finalized) {
return this.module.exports;
} else {
var result = this.callback.apply(this, reifiedDeps);
if (!(this.hasExportsAsDep && result === undefined)) {
this.module.exports = result;
}
this.makeDefaultExport();
this.finalized = true;
return this.module.exports;
}
};
Module.prototype.unsee = function() {
this.finalized = false;
this.state = undefined;
this.module = { exports: {}};
};
Module.prototype.reify = function() {
var deps = this.deps;
var length = deps.length;
var reified = new Array(length);
var dep;
for (var i = 0, l = length; i < l; i++) {
dep = deps[i];
if (dep === 'exports') {
this.hasExportsAsDep = true;
reified[i] = this.module.exports;
} else if (dep === 'require') {
reified[i] = this.makeRequire();
} else if (dep === 'module') {
reified[i] = this.module;
} else {
reified[i] = findModule(resolve(dep, this.name), this.name).module.exports;
}
}
return reified;
};
Module.prototype.makeRequire = function() {
var name = this.name;
return this._require || (this._require = function(dep) {
return require(resolve(dep, name));
});
};
Module.prototype.build = function() {
if (this.state === FAILED) { return; }
this.state = FAILED;
this.exports(this.reify());
this.state = LOADED;
};
define = function(name, deps, callback) {
if (arguments.length < 2) {
unsupportedModule(arguments.length);
}
if (!_isArray(deps)) {
callback = deps;
deps = [];
}
registry[name] = new Module(name, deps, callback);
};
// we don't support all of AMD
// define.amd = {};
// we will support petals...
define.petal = { };
function Alias(path) {
this.name = path;
}
define.alias = function(path) {
return new Alias(path);
};
function missingModule(name, referrer) {
throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`');
}
requirejs = require = requireModule = function(name) {
return findModule(name, '(require)').module.exports;
};
function findModule(name, referrer) {
var mod = registry[name] || registry[name + '/index'];
while (mod && mod.callback instanceof Alias) {
name = mod.callback.name;
mod = registry[name];
}
if (!mod) { missingModule(name, referrer); }
mod.build();
return mod;
}
function resolve(child, name) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split('/');
var nameParts = name.split('/');
var parentBase = nameParts.slice(0, -1);
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (part === '..') {
if (parentBase.length === 0) {
throw new Error('Cannot access parent module of root');
}
parentBase.pop();
} else if (part === '.') {
continue;
} else { parentBase.push(part); }
}
return parentBase.join('/');
}
requirejs.entries = requirejs._eak_seen = registry;
requirejs.unsee = function(moduleName) {
findModule(moduleName, '(unsee)').unsee();
};
requirejs.clear = function() {
requirejs.entries = requirejs._eak_seen = registry = {};
seen = {};
};
})();
define("ember", ["exports"], function (exports) {
exports["default"] = Ember;
});
define("ember-data", ["exports"], function (exports) {
exports["default"] = DS;
});
define('active-model-adapter', ['exports', 'ember', 'ember-data'], function (exports, _ember, _emberData) {
var InvalidError = _emberData["default"].InvalidError;
var errorsHashToArray = _emberData["default"].errorsHashToArray;
var RESTAdapter = _emberData["default"].RESTAdapter;
var _Ember$String = _ember["default"].String;
var pluralize = _Ember$String.pluralize;
var decamelize = _Ember$String.decamelize;
var underscore = _Ember$String.underscore;
/**
@module ember-data
*/
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
Unlike the DS.RESTAdapter, async relationship keys must be the singular form
of the relationship name, followed by "_id" for DS.belongsTo relationships,
or "_ids" for DS.hasMany relationships.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
**/
var ActiveModelAdapter = RESTAdapter.extend({
defaultSerializer: '-active-model',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} modelName
@return String
*/
pathForType: function (modelName) {
var decamelized = decamelize(modelName);
var underscored = underscore(decamelized);
return pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `handleResponse` method
to format errors passed to a DS.InvalidError for all
422 Unprocessable Entity responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method handleResponse
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Object | DS.AdapterError} response
*/
handleResponse: function (status, headers, payload) {
if (this.isInvalid(status, headers, payload)) {
var errors = errorsHashToArray(payload.errors);
return new InvalidError(errors);
} else {
return this._super.apply(this, arguments);
}
}
});
exports["default"] = ActiveModelAdapter;
});
define('active-model-serializer', ['exports', 'ember-data', 'ember'], function (exports, _emberData, _ember) {
/**
@module ember-data
*/
var _Ember$String = _ember["default"].String;
var singularize = _Ember$String.singularize;
var classify = _Ember$String.classify;
var decamelize = _Ember$String.decamelize;
var pluralize = _Ember$String.pluralize;
var camelize = _Ember$String.camelize;
var underscore = _Ember$String.underscore;
var RESTSerializer = _emberData["default"].RESTSerializer;
var normalizeModelName = _emberData["default"].normalizeModelName;
/**
The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This serializer extends the DS.RESTSerializer by making consistent
use of the camelization, decamelization and pluralization methods to
normalize the serialized JSON into a format that is compatible with
a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelSerializer expects the JSON returned from your server
to follow the REST adapter conventions substituting underscored keys
for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelSerializer
@namespace DS
@extends DS.RESTSerializer
*/
var ActiveModelSerializer = RESTSerializer.extend({
// SERIALIZE
/**
Converts camelCased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@return String
*/
keyForAttribute: function (attr) {
return decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} relationshipModelName
@param {String} kind
@return String
*/
keyForRelationship: function (relationshipModelName, kind) {
var key = decamelize(relationshipModelName);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
},
/**
`keyForLink` can be used to define a custom key when deserializing link
properties. The `ActiveModelSerializer` camelizes link keys by default.
@method keyForLink
@param {String} key
@param {String} kind `belongsTo` or `hasMany`
@return {String} normalized key
*/
keyForLink: function (key, relationshipKind) {
return camelize(key);
},
/*
Does not serialize hasMany relationships by default.
*/
serializeHasMany: function () {},
/**
Underscores the JSON root keys when serializing.
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
payloadKeyFromModelName: function (modelName) {
return underscore(decamelize(modelName));
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = underscore(key + "_type");
if (_ember["default"].isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = classify(belongsTo.modelName).replace('/', '::');
}
},
/**
Add extra step to `DS.RESTSerializer.normalize` so links are normalized.
If your payload looks like:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} typeClass
@param {Object} hash
@param {String} prop
@return Object
*/
normalize: function (typeClass, hash, prop) {
this.normalizeLinks(hash);
return this._super(typeClass, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
*/
normalizeLinks: function (data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
* @private
*/
_keyForIDLessRelationship: function (key, relationshipType, type) {
if (relationshipType === 'hasMany') {
return underscore(pluralize(key));
} else {
return underscore(singularize(key));
}
},
extractRelationships: function (modelClass, resourceHash) {
modelClass.eachRelationship(function (key, relationshipMeta) {
var relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, "deserialize");
var idLessKey = this._keyForIDLessRelationship(key, relationshipMeta.kind, "deserialize");
// converts post to post_id, posts to post_ids
if (resourceHash[idLessKey] && typeof relationshipMeta[relationshipKey] === 'undefined') {
resourceHash[relationshipKey] = resourceHash[idLessKey];
}
// prefer the format the AMS gem expects, e.g.:
// relationship: {id: id, type: type}
if (relationshipMeta.options.polymorphic) {
extractPolymorphicRelationships(key, relationshipMeta, resourceHash, relationshipKey);
}
// If the preferred format is not found, use {relationship_name_id, relationship_name_type}
if (resourceHash.hasOwnProperty(relationshipKey) && typeof resourceHash[relationshipKey] !== 'object') {
var polymorphicTypeKey = this.keyForRelationship(key) + '_type';
if (resourceHash[polymorphicTypeKey] && relationshipMeta.options.polymorphic) {
var id = resourceHash[relationshipKey];
var type = resourceHash[polymorphicTypeKey];
delete resourceHash[polymorphicTypeKey];
delete resourceHash[relationshipKey];
resourceHash[relationshipKey] = { id: id, type: type };
}
}
}, this);
return this._super.apply(this, arguments);
},
modelNameFromPayloadKey: function (key) {
var convertedFromRubyModule = singularize(key.replace('::', '/'));
return normalizeModelName(convertedFromRubyModule);
}
});
function extractPolymorphicRelationships(key, relationshipMeta, resourceHash, relationshipKey) {
var polymorphicKey = decamelize(key);
var hash = resourceHash[polymorphicKey];
if (hash !== null && typeof hash === 'object') {
resourceHash[relationshipKey] = hash;
}
}
exports["default"] = ActiveModelSerializer;
});
define('index', ['exports', './active-model-adapter', './active-model-serializer'], function (exports, _activeModelAdapter, _activeModelSerializer) {
exports["default"] = _activeModelAdapter["default"];
exports.ActiveModelAdapter = _activeModelAdapter["default"];
exports.ActiveModelSerializer = _activeModelSerializer["default"];
});
define("initializers/active-model-adapter", ["exports", "active-model-adapter", "active-model-serializer"], function (exports, _activeModelAdapter, _activeModelAdapterActiveModelSerializer) {
exports["default"] = {
name: 'active-model-adapter',
initialize: function () {
var application = arguments[1] || arguments[0];
application.register('adapter:-active-model', _activeModelAdapter["default"]);
application.register('serializer:-active-model', _activeModelAdapterActiveModelSerializer["default"]);
}
};
});
define('globals', ['exports', './index', 'initializers/active-model-adapter', 'ember', 'ember-data'], function (exports, _index, _initializersActiveModelAdapter, _ember, _emberData) {
_emberData["default"].ActiveModelAdapter = _index.ActiveModelAdapter;
_emberData["default"].ActiveModelSerializer = _index.ActiveModelSerializer;
_ember["default"].Application.initializer(_initializersActiveModelAdapter["default"]);
});
// this file is used to generate the globals build.
// DO NOT try to use this in your app.
require("globals");
})();