dist/globals/ember-data.prod.js in ember-data-source-2.6.2 vs dist/globals/ember-data.prod.js in ember-data-source-2.7.0.beta.1
- old
+ new
@@ -4,11 +4,11 @@
/*!
* @overview Ember Data
* @copyright Copyright 2011-2016 Tilde Inc. and contributors.
* Portions Copyright 2011 LivingSocial Inc.
* @license Licensed under MIT license (see license.js)
- * @version 2.6.2
+ * @version 2.7.0-beta.1
*/
var loader, define, requireModule, require, requirejs;
(function(global) {
@@ -23,38 +23,30 @@
requirejs: requirejs
};
requirejs = require = requireModule = function(name) {
stats.require++;
- var pending = [];
- var mod = findModule(name, '(require)', pending);
-
- for (var i = pending.length - 1; i >= 0; i--) {
- pending[i].exports();
- }
-
- return mod.module.exports;
+ return findModule(name, '(require)').module.exports;
};
function resetStats() {
stats = {
define: 0,
require: 0,
reify: 0,
- findDeps: 0,
+ build: 0,
modules: 0,
exports: 0,
+ ensureBuild: 0,
resolve: 0,
resolveRelative: 0,
findModule: 0,
- pendingQueueLength: 0
};
requirejs._stats = stats;
}
var stats;
-
resetStats();
loader = {
noConflict: function(aliases) {
var oldName, newName;
@@ -81,10 +73,12 @@
_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: `' +
@@ -92,22 +86,21 @@
}
var defaultDeps = ['require', 'exports', 'module'];
function Module(name, deps, callback, alias) {
- stats.modules++;
+ stats.modules ++;
this.id = uuid++;
this.name = name;
this.deps = !deps.length && callback.length ? defaultDeps : deps;
this.module = { exports: {} };
this.callback = callback;
+ this.state = undefined;
this.finalized = false;
this.hasExportsAsDep = false;
this.isAlias = alias;
this.reified = new Array(deps.length);
- this._foundDeps = false;
- this.isPending = false;
}
Module.prototype.makeDefaultExport = function() {
var exports = this.module.exports;
if (exports !== null &&
@@ -116,70 +109,50 @@
exports['default'] = exports;
}
};
Module.prototype.exports = function() {
- if (this.finalized) { return this.module.exports; }
- stats.exports++;
-
- this.finalized = true;
- this.isPending = false;
-
- if (loader.wrapModules) {
- this.callback = loader.wrapModules(this.name, this.callback);
+ stats.exports ++;
+ if (this.finalized) {
+ return this.module.exports;
+ } else {
+ if (loader.wrapModules) {
+ this.callback = loader.wrapModules(this.name, this.callback);
+ }
+ var result = this.callback.apply(this, this.reified);
+ if (!(this.hasExportsAsDep && result === undefined)) {
+ this.module.exports = result;
+ }
+ this.makeDefaultExport();
+ this.finalized = true;
+ return this.module.exports;
}
-
- this.reify();
-
- var result = this.callback.apply(this, this.reified);
-
- if (!(this.hasExportsAsDep && result === undefined)) {
- this.module.exports = result;
- }
- this.makeDefaultExport();
- return this.module.exports;
};
Module.prototype.unsee = function() {
this.finalized = false;
- this._foundDeps = false;
- this.isPending = false;
+ this.state = undefined;
this.module = { exports: {}};
};
Module.prototype.reify = function() {
stats.reify++;
+ var deps = this.deps;
+ var dep;
var reified = this.reified;
- for (var i = 0; i < reified.length; i++) {
- var mod = reified[i];
- reified[i] = mod.exports ? mod.exports : mod.module.exports();
- }
- };
- Module.prototype.findDeps = function(pending) {
- if (this._foundDeps) {
- return;
- }
-
- stats.findDeps++;
- this._foundDeps = true;
- this.isPending = true;
-
- var deps = this.deps;
-
for (var i = 0; i < deps.length; i++) {
- var dep = deps[i];
- var entry = this.reified[i] = { exports: undefined, module: undefined };
+ dep = deps[i];
if (dep === 'exports') {
this.hasExportsAsDep = true;
- entry.exports = this.module.exports;
+ reified[i] = this.module.exports;
} else if (dep === 'require') {
- entry.exports = this.makeRequire();
+ reified[i] = this.makeRequire();
} else if (dep === 'module') {
- entry.exports = this.module;
+ reified[i] = this.module;
} else {
- entry.module = findModule(resolve(dep, this.name), this.name, pending);
+ reified[i] = findModule(resolve(dep, this.name), this.name).module.exports;
}
}
};
Module.prototype.makeRequire = function() {
@@ -192,10 +165,20 @@
return has(resolve(dep, name));
}
return r;
};
+ Module.prototype.build = function() {
+ stats.ensureBuild++;
+ if (this.state === FAILED || this.state === LOADED) { return; }
+ stats.build++;
+ this.state = FAILED;
+ this.reify()
+ this.exports();
+ this.state = LOADED;
+ };
+
define = function(name, deps, callback) {
stats.define++;
if (arguments.length < 2) {
unsupportedModule(arguments.length);
}
@@ -227,25 +210,21 @@
function missingModule(name, referrer) {
throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`');
}
- function findModule(name, referrer, pending) {
+ function findModule(name, referrer) {
stats.findModule++;
var mod = registry[name] || registry[name + '/index'];
while (mod && mod.isAlias) {
mod = registry[mod.name];
}
if (!mod) { missingModule(name, referrer); }
- if (pending && !mod.finalized && !mod.isPending) {
- mod.findDeps(pending);
- pending.push(mod);
- stats.pendingQueueLength++;
- }
+ mod.build();
return mod;
}
function resolve(child, name) {
stats.resolve++;
@@ -277,11 +256,11 @@
}
requirejs.entries = requirejs._eak_seen = registry;
requirejs.has = has;
requirejs.unsee = function(moduleName) {
- findModule(moduleName, '(unsee)', false).unsee();
+ findModule(moduleName, '(unsee)').unsee();
};
requirejs.clear = function() {
resetStats();
requirejs.entries = requirejs._eak_seen = registry = {};
@@ -619,11 +598,12 @@
@property VERSION
@type String
@static
*/
var DS = _ember.default.Namespace.create({
- VERSION: _emberDataVersion.default
+ VERSION: _emberDataVersion.default,
+ name: "DS"
});
if (_ember.default.libraries) {
_ember.default.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
@@ -709,42 +689,26 @@
var assertionMessage = 'You cannot add a record of type \'' + addedType + '\' to the \'' + recordType + '.' + key + '\' relationship (only \'' + typeClass.modelName + '\' allowed)';
assert(assertionMessage, checkPolymorphic(typeClass, addedRecord));
}
});
-define('ember-data/-private/ext/date', ['exports', 'ember'], function (exports, _ember) {
+define('ember-data/-private/ext/date', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) {
- /**
- Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
-
- © 2011 Colin Snover <http://zetafleet.com>
-
- Released under MIT license.
-
- @class Date
- @namespace Ember
- @static
- */
_ember.default.Date = _ember.default.Date || {};
var origParse = Date.parse;
var numericKeys = [1, 4, 5, 6, 7, 10, 11];
- /**
- @method parse
- @param {Date} date
- @return {Number} timestamp
- */
- _ember.default.Date.parse = function (date) {
+ var parseDate = function (date) {
var timestamp, struct;
var minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
- if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date)) {
+ if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?:(\d{2}))?)?)?$/.exec(date)) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; k = numericKeys[i]; ++i) {
struct[k] = +struct[k] || 0;
}
@@ -766,12 +730,20 @@
}
return timestamp;
};
+ exports.parseDate = parseDate;
+ _ember.default.Date.parse = function (date) {
+
+ return parseDate(date);
+
+ // throw deprecation
+ };
+
if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.Date) {
- Date.parse = _ember.default.Date.parse;
+ Date.parse = parseDate;
}
});
/**
@module ember-data
*/
@@ -782,10 +754,29 @@
var _Ember$FEATURES;
return (_Ember$FEATURES = _ember.default.FEATURES).isEnabled.apply(_Ember$FEATURES, arguments);
}
});
+define('ember-data/-private/global', ['exports'], function (exports) {
+ /* globals global, window, self */
+
+ // originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js
+
+ // from lodash to catch fake globals
+ function checkGlobal(value) {
+ return value && value.Object === Object ? value : undefined;
+ }
+
+ // element ids can ruin global miss checks
+ function checkElementIdShadowing(value) {
+ return value && value.nodeType === undefined ? value : undefined;
+ }
+
+ // export real global
+ exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')();
+ // eval outside of strict mode
+});
define("ember-data/-private/initializers/data-adapter", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) {
exports.default = initializeDebugAdapter;
/**
Configures a registry with injections on Ember applications
@@ -919,11 +910,11 @@
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function coerceId(id) {
- return id == null || id === '' ? null : id + '';
+ return id === null || id === undefined || id === '' ? null : id + '';
}
});
define('ember-data/-private/system/container-proxy', ['exports', 'ember-data/-private/debug'], function (exports, _emberDataPrivateDebug) {
exports.default = ContainerProxy;
@@ -2101,11 +2092,11 @@
has: function (attribute) {
return !isEmpty(this.errorsFor(attribute));
}
});
});
-define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/features", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) {
+define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) {
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })();
exports.default = InternalModel;
var Promise = _ember.default.RSVP.Promise;
@@ -2910,16 +2901,13 @@
if (this.record) {
return this.record.toString();
} else {
return "<" + this.modelName + ":" + this.id + ">";
}
- }
- };
+ },
- if (true) {
-
- InternalModel.prototype.referenceFor = function (type, name) {
+ referenceFor: function (type, name) {
var reference = this.references[name];
if (!reference) {
var relationship = this._relationships.get(name);
@@ -2931,14 +2919,14 @@
this.references[name] = reference;
}
return reference;
- };
- }
+ }
+ };
});
-define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/features", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateFeatures, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr) {
+define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr) {
/**
@module ember-data
*/
@@ -3408,10 +3396,26 @@
});
}
}
});
```
+ If you pass an object on the `adapterOptions` property of the options
+ argument it will be passed to you adapter via the snapshot
+ ```js
+ record.destroyRecord({ adapterOptions: { subscribe: false } });
+ ```
+ ```app/adapters/post.js
+ import MyCustomAdapter from './custom-adapter';
+ export default MyCustomAdapter.extend({
+ deleteRecord: function(store, type, snapshot) {
+ if (snapshot.adapterOptions.subscribe) {
+ // ...
+ }
+ // ...
+ }
+ });
+ ```
@method destroyRecord
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
@@ -3538,11 +3542,27 @@
// Success callback
}, function() {
// Error callback
});
```
- @method save
+ If you pass an object on the `adapterOptions` property of the options
+ argument it will be passed to you adapter via the snapshot
+ ```js
+ record.save({ adapterOptions: { subscribe: false } });
+ ```
+ ```app/adapters/post.js
+ import MyCustomAdapter from './custom-adapter';
+ export default MyCustomAdapter.extend({
+ updateRecord: function(store, type, snapshot) {
+ if (snapshot.adapterOptions.subscribe) {
+ // ...
+ }
+ // ...
+ }
+ });
+ ```
+ @method save
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function (options) {
@@ -3619,13 +3639,108 @@
var constructor = this.constructor;
},
attr: function () {},
- belongsTo: function () {},
+ /**
+ Get the reference for the specified belongsTo relationship.
+ Example
+ ```javascript
+ // models/blog.js
+ export default DS.Model.extend({
+ user: DS.belongsTo({ async: true })
+ });
+ var blog = store.push({
+ type: 'blog',
+ id: 1,
+ relationships: {
+ user: { type: 'user', id: 1 }
+ }
+ });
+ var userRef = blog.belongsTo('user');
+ // check if the user relationship is loaded
+ var isLoaded = userRef.value() !== null;
+ // get the record of the reference (null if not yet available)
+ var user = userRef.value();
+ // get the identifier of the reference
+ if (userRef.remoteType() === "id") {
+ var id = userRef.id();
+ } else if (userRef.remoteType() === "link") {
+ var link = userRef.link();
+ }
+ // load user (via store.findRecord or store.findBelongsTo)
+ userRef.load().then(...)
+ // or trigger a reload
+ userRef.reload().then(...)
+ // provide data for reference
+ userRef.push({
+ type: 'user',
+ id: 1,
+ attributes: {
+ username: "@user"
+ }
+ }).then(function(user) {
+ userRef.value() === user;
+ });
+ ```
+ @method belongsTo
+ @param {String} name of the relationship
+ @since 2.5.0
+ @return {BelongsToReference} reference for this relationship
+ */
+ belongsTo: function (name) {
+ return this._internalModel.referenceFor('belongsTo', name);
+ },
- hasMany: function () {},
+ /**
+ Get the reference for the specified hasMany relationship.
+ Example
+ ```javascript
+ // models/blog.js
+ export default DS.Model.extend({
+ comments: DS.hasMany({ async: true })
+ });
+ var blog = store.push({
+ type: 'blog',
+ id: 1,
+ relationships: {
+ comments: {
+ data: [
+ { type: 'comment', id: 1 },
+ { type: 'comment', id: 2 }
+ ]
+ }
+ }
+ });
+ var commentsRef = blog.hasMany('comments');
+ // check if the comments are loaded already
+ var isLoaded = commentsRef.value() !== null;
+ // get the records of the reference (null if not yet available)
+ var comments = commentsRef.value();
+ // get the identifier of the reference
+ if (commentsRef.remoteType() === "ids") {
+ var ids = commentsRef.ids();
+ } else if (commentsRef.remoteType() === "link") {
+ var link = commentsRef.link();
+ }
+ // load comments (via store.findMany or store.findHasMany)
+ commentsRef.load().then(...)
+ // or trigger a reload
+ commentsRef.reload().then(...)
+ // provide data for reference
+ commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) {
+ commentsRef.value() === comments;
+ });
+ ```
+ @method hasMany
+ @param {String} name of the relationship
+ @since 2.5.0
+ @return {HasManyReference} reference for this relationship
+ */
+ hasMany: function (name) {
+ return this._internalModel.referenceFor('hasMany', name);
+ },
setId: _ember.default.observer('id', function () {
this._internalModel.setId(this.get('id'));
})
});
@@ -3694,113 +3809,10 @@
return this.store.container;
}
});
}
- if (true) {
-
- Model.reopen({
-
- /**
- Get the reference for the specified belongsTo relationship.
- Example
- ```javascript
- // models/blog.js
- export default DS.Model.extend({
- user: DS.belongsTo({ async: true })
- });
- var blog = store.push({
- type: 'blog',
- id: 1,
- relationships: {
- user: { type: 'user', id: 1 }
- }
- });
- var userRef = blog.belongsTo('user');
- // check if the user relationship is loaded
- var isLoaded = userRef.value() !== null;
- // get the record of the reference (null if not yet available)
- var user = userRef.value();
- // get the identifier of the reference
- if (userRef.remoteType() === "id") {
- var id = userRef.id();
- } else if (userRef.remoteType() === "link") {
- var link = userRef.link();
- }
- // load user (via store.findRecord or store.findBelongsTo)
- userRef.load().then(...)
- // or trigger a reload
- userRef.reload().then(...)
- // provide data for reference
- userRef.push({
- type: 'user',
- id: 1,
- attributes: {
- username: "@user"
- }
- }).then(function(user) {
- userRef.value() === user;
- });
- ```
- @method belongsTo
- @param {String} name of the relationship
- @return {BelongsToReference} reference for this relationship
- */
- belongsTo: function (name) {
- return this._internalModel.referenceFor('belongsTo', name);
- },
-
- /**
- Get the reference for the specified hasMany relationship.
- Example
- ```javascript
- // models/blog.js
- export default DS.Model.extend({
- comments: DS.hasMany({ async: true })
- });
- var blog = store.push({
- type: 'blog',
- id: 1,
- relationships: {
- comments: {
- data: [
- { type: 'comment', id: 1 },
- { type: 'comment', id: 2 }
- ]
- }
- }
- });
- var commentsRef = blog.hasMany('comments');
- // check if the comments are loaded already
- var isLoaded = commentsRef.value() !== null;
- // get the records of the reference (null if not yet available)
- var comments = commentsRef.value();
- // get the identifier of the reference
- if (commentsRef.remoteType() === "ids") {
- var ids = commentsRef.ids();
- } else if (commentsRef.remoteType() === "link") {
- var link = commentsRef.link();
- }
- // load comments (via store.findMany or store.findHasMany)
- commentsRef.load().then(...)
- // or trigger a reload
- commentsRef.reload().then(...)
- // provide data for reference
- commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) {
- commentsRef.value() === comments;
- });
- ```
- @method hasMany
- @param {String} name of the relationship
- @return {HasManyReference} reference for this relationship
- */
- hasMany: function (name) {
- return this._internalModel.referenceFor('hasMany', name);
- }
- });
- }
-
Model.reopenClass(_emberDataPrivateSystemRelationshipsExt.RelationshipsClassMethodsMixin);
Model.reopenClass(_emberDataPrivateSystemModelAttr.AttrClassMethodsMixin);
exports.default = Model.extend(_emberDataPrivateSystemDebugDebugInfo.default, _emberDataPrivateSystemRelationshipsBelongsTo.BelongsToMixin, _emberDataPrivateSystemRelationshipsExt.DidDefinePropertyMixin, _emberDataPrivateSystemRelationshipsExt.RelationshipsInstanceMethodsMixin, _emberDataPrivateSystemRelationshipsHasMany.HasManyMixin, _emberDataPrivateSystemModelAttr.AttrInstanceMethodsMixin);
});
@@ -4541,11 +4553,10 @@
internalModel.triggerLater('didCommit', internalModel);
}
};
function wireState(object, parent, name) {
- /*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = mixin(parent ? Object.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
@@ -4638,11 +4649,11 @@
return;
}
presenceSet[guid] = true;
- if (idx === undefined || idx == null) {
+ if (idx === undefined || idx === null) {
list.push(obj);
} else {
list.splice(idx, 0, obj);
}
@@ -5180,13 +5191,11 @@
isLoaded: true,
isUpdating: false,
meta: (0, _emberDataPrivateSystemCloneNull.default)(payload.meta)
});
- if (false) {
- this.set('links', (0, _emberDataPrivateSystemCloneNull.default)(payload.links));
- }
+ this.set('links', (0, _emberDataPrivateSystemCloneNull.default)(payload.links));
internalModels.forEach(function (record) {
_this.manager.recordArraysForRecord(record).add(_this);
});
@@ -5463,11 +5472,11 @@
define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _emberDataPrivateSystemReferencesRecord, _emberDataPrivateSystemReferencesBelongsTo, _emberDataPrivateSystemReferencesHasMany) {
exports.RecordReference = _emberDataPrivateSystemReferencesRecord.default;
exports.BelongsToReference = _emberDataPrivateSystemReferencesBelongsTo.default;
exports.HasManyReference = _emberDataPrivateSystemReferencesHasMany.default;
});
-define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug) {
+define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateFeatures, _emberDataPrivateDebug) {
var BelongsToReference = function (store, parentInternalModel, belongsToRelationship) {
this._super$constructor(store, parentInternalModel);
this.belongsToRelationship = belongsToRelationship;
this.type = belongsToRelationship.relationshipMeta.type;
@@ -5551,11 +5560,11 @@
});
};
exports.default = BelongsToReference;
});
-define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug) {
+define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug, _emberDataPrivateFeatures) {
var get = _ember.default.get;
var HasManyReference = function (store, parentInternalModel, hasManyRelationship) {
this._super$constructor(store, parentInternalModel);
@@ -5598,20 +5607,31 @@
HasManyReference.prototype.push = function (objectOrPromise) {
var _this = this;
return _ember.default.RSVP.resolve(objectOrPromise).then(function (payload) {
var array = payload;
+
+ var useLegacyArrayPush = true;
if (typeof payload === "object" && payload.data) {
array = payload.data;
+ useLegacyArrayPush = array.length && array[0].data;
}
- var internalModels = array.map(function (obj) {
- var record = _this.store.push(obj);
+ useLegacyArrayPush = true;
- return record._internalModel;
- });
+ var internalModels = undefined;
+ if (useLegacyArrayPush) {
+ internalModels = array.map(function (obj) {
+ var record = _this.store.push(obj);
+ return record._internalModel;
+ });
+ } else {
+ var records = _this.store.push(payload);
+ internalModels = _ember.default.A(records).mapBy('_internalModel');
+ }
+
_this.hasManyRelationship.computeChanges(internalModels);
return _this.hasManyRelationship.manyArray;
});
};
@@ -6286,13 +6306,13 @@
```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 }
+ //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true }
relationshipsByName.get('owner');
- //=> { key: 'owner', kind: 'belongsTo', type: App.User }
+ //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
@@ -6381,18 +6401,18 @@
determineRelationshipType: function (knownSide, store) {
var knownKey = knownSide.key;
var knownKind = knownSide.kind;
var inverse = this.inverseFor(knownKey, store);
- var key = undefined,
- otherKind = undefined;
+ // let key;
+ var otherKind = undefined;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
- key = inverse.name;
+ // key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
@@ -6418,11 +6438,11 @@
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
+ - **type** <span class="type">String</span> the type name 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';
@@ -7320,12 +7340,15 @@
setHasLoaded: function (value) {
this.hasLoaded = value;
}
};
});
-define('ember-data/-private/system/snapshot-record-array', ['exports', 'ember-data/-private/features'], function (exports, _emberDataPrivateFeatures) {
+define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) {
exports.default = SnapshotRecordArray;
+ /**
+ @module ember-data
+ */
/**
@class SnapshotRecordArray
@namespace DS
@private
@@ -7374,13 +7397,11 @@
@property adapterOptions
@type {Object}
*/
this.adapterOptions = options.adapterOptions;
- if (true) {
- this.include = options.include;
- }
+ this.include = options.include;
}
/**
Get snapshots of the underlying record array
@method snapshots
@@ -7394,14 +7415,11 @@
this._snapshots = recordArray.invoke('createSnapshot');
return this._snapshots;
};
});
-/**
- @module ember-data
-*/
-define('ember-data/-private/system/snapshot', ['exports', 'ember', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) {
+define("ember-data/-private/system/snapshot", ["exports", "ember", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemEmptyObject) {
exports.default = Snapshot;
var get = _ember.default.get;
/**
@@ -7439,13 +7457,11 @@
@property adapterOptions
@type {Object}
*/
this.adapterOptions = options.adapterOptions;
- if (true) {
- this.include = options.include;
- }
+ this.include = options.include;
this._changedAttributes = record.changedAttributes();
}
Snapshot.prototype = {
@@ -7726,11 +7742,11 @@
});
/**
@module ember-data
*/
define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/model', 'ember-data/-private/debug', 'ember-data/-private/system/normalize-link', 'ember-data/-private/system/normalize-model-name', 'ember-data/adapters/errors', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataModel, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeLink, _emberDataPrivateSystemNormalizeModelName, _emberDataAdaptersErrors, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers, _emberDataPrivateSystemStoreFinders, _emberDataPrivateUtils, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateSystemStoreContainerInstanceCache, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) {
- var badIdFormatAssertion = '`id` has to be non-empty string or number';
+ var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number';
exports.badIdFormatAssertion = badIdFormatAssertion;
var Backburner = _ember.default._Backburner;
var Map = _ember.default.Map;
@@ -8070,10 +8086,11 @@
```
If the record is not yet available, the store will ask the adapter's `find`
method to find the necessary data. If the record is already present in the
store, it depends on the reload behavior _when_ the returned promise
resolves.
+ ### Reloading
The reload behavior is configured either via the passed `options` hash or
the result of the adapter's `shouldReloadRecord`.
If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates
to `true`, then the returned promise resolves once the adapter returns
data, regardless if the requested record is already in the store:
@@ -8097,10 +8114,11 @@
post.get("revision"); // 2
});
```
If no reload is indicated via the abovementioned ways, then the promise
immediately resolves with the cached version in the store.
+ ### Background Reloading
Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,
then a background reload is started, which updates the records' data, once
it is available:
```js
// app/adapters/post.js
@@ -8132,10 +8150,44 @@
// revision: 2
// }
// ]
blogPost.get('revision'); // 2
```
+ If you would like to force or prevent background reloading, you can set a
+ boolean value for `backgroundReload` in the options object for
+ `findRecord`.
+ ```app/routes/post/edit.js
+ import Ember from 'ember';
+ export default Ember.Route.extend({
+ model: function(params) {
+ return this.store.findRecord('post', params.post_id, { backgroundReload: false });
+ }
+ });
+ ```
+ If you pass an object on the `adapterOptions` property of the options
+ argument it will be passed to you adapter via the snapshot
+ ```app/routes/post/edit.js
+ import Ember from 'ember';
+ export default Ember.Route.extend({
+ model: function(params) {
+ return this.store.findRecord('post', params.post_id, {
+ adapterOptions: { subscribe: false }
+ });
+ }
+ });
+ ```
+ ```app/adapters/post.js
+ import MyCustomAdapter from './custom-adapter';
+ export default MyCustomAdapter.extend({
+ findRecord: function(store, type, id, snapshot) {
+ if (snapshot.adapterOptions.subscribe) {
+ // ...
+ }
+ // ...
+ }
+ });
+ ```
See [peekRecord](#method_peekRecord) to get the cached version of a record.
@method findRecord
@param {String} modelName
@param {(String|Integer)} id
@param {Object} options
@@ -8159,20 +8211,25 @@
// Refetch if the reload option is passed
if (options.reload) {
return this.scheduleFetch(internalModel, options);
}
- // Refetch the record if the adapter thinks the record is stale
var snapshot = internalModel.createSnapshot(options);
var typeClass = internalModel.type;
var adapter = this.adapterFor(typeClass.modelName);
+
+ // Refetch the record if the adapter thinks the record is stale
if (adapter.shouldReloadRecord(this, snapshot)) {
return this.scheduleFetch(internalModel, options);
}
- // Trigger the background refetch if all the previous checks fail
- if (adapter.shouldBackgroundReloadRecord(this, snapshot)) {
+ if (options.backgroundReload === false) {
+ return Promise.resolve(internalModel);
+ }
+
+ // Trigger the background refetch if backgroundReload option is passed
+ if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) {
this.scheduleFetch(internalModel, options);
}
// Return the cached record
return Promise.resolve(internalModel);
@@ -8371,10 +8428,42 @@
pendingFetchItems.forEach(_fetchRecord);
}
},
/**
+ Get the reference for the specified record.
+ Example
+ ```javascript
+ var userRef = store.getReference('user', 1);
+ // check if the user is loaded
+ var isLoaded = userRef.value() !== null;
+ // get the record of the reference (null if not yet available)
+ var user = userRef.value();
+ // get the identifier of the reference
+ if (userRef.remoteType() === "id") {
+ var id = userRef.id();
+ }
+ // load user (via store.find)
+ userRef.load().then(...)
+ // or trigger a reload
+ userRef.reload().then(...)
+ // provide data for reference
+ userRef.push({ id: 1, username: "@user" }).then(function(user) {
+ userRef.value() === user;
+ });
+ ```
+ @method getReference
+ @param {String} type
+ @param {String|Integer} id
+ @since 2.5.0
+ @return {RecordReference}
+ */
+ getReference: function (type, id) {
+ return this._internalModelForId(type, id).recordReference;
+ },
+
+ /**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
_Note: This is an synchronous method and does not return a promise._
@@ -8635,11 +8724,11 @@
return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)((0, _emberDataPrivateSystemStoreFinders._queryRecord)(adapter, this, typeClass, query));
},
/**
- `findAll` ask the adapter's `findAll` method to find the records for the
+ `findAll` asks the adapter's `findAll` method to find the records for the
given type, and returns a promise which will resolve with all records of
this type present in the store, even if the adapter only returns a subset
of them.
```app/routes/authors.js
import Ember from 'ember';
@@ -8650,10 +8739,11 @@
});
```
_When_ the returned promise resolves depends on the reload behavior,
configured via the passed `options` hash and the result of the adapter's
`shouldReloadAll` method.
+ ### Reloading
If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to
`true`, then the returned promise resolves once the adapter returns data,
regardless if there are already records in the store:
```js
store.push({
@@ -8673,11 +8763,12 @@
authors.getEach("id"); // ['first', 'second']
});
```
If no reload is indicated via the abovementioned ways, then the promise
immediately resolves with all the records currently loaded in the store.
- Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,
+ ### Background Reloading
+ Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,
then a background reload is started. Once this resolves, the array with
which the promise resolves, is updated automatically so it contains all the
records in the store:
```js
// app/adapters/application.js
@@ -8708,11 +8799,45 @@
// type: 'author'
// }
// ]
allAuthors.getEach('id'); // ['first', 'second']
```
- See [peekAll](#method_peekAll) to get an array of current records in the
+ If you would like to force or prevent background reloading, you can set a
+ boolean value for `backgroundReload` in the options object for
+ `findAll`.
+ ```app/routes/post/edit.js
+ import Ember from 'ember';
+ export default Ember.Route.extend({
+ model: function() {
+ return this.store.findAll('post', { backgroundReload: false });
+ }
+ });
+ ```
+ If you pass an object on the `adapterOptions` property of the options
+ argument it will be passed to you adapter via the `snapshotRecordArray`
+ ```app/routes/posts.js
+ import Ember from 'ember';
+ export default Ember.Route.extend({
+ model: function(params) {
+ return this.store.findAll('post', {
+ adapterOptions: { subscribe: false }
+ });
+ }
+ });
+ ```
+ ```app/adapters/post.js
+ import MyCustomAdapter from './custom-adapter';
+ export default MyCustomAdapter.extend({
+ findAll: function(store, type, sinceToken, snapshotRecordArray) {
+ if (snapshotRecordArray.adapterOptions.subscribe) {
+ // ...
+ }
+ // ...
+ }
+ });
+ ```
+ See [peekAll](#method_peekAll) to get an array of current records in the
store, without waiting until a reload is finished.
See [query](#method_query) to only get a subset of records from the server.
@method findAll
@param {String} modelName
@param {Object} options
@@ -8739,17 +8864,25 @@
set(array, 'isUpdating', true);
if (options.reload) {
return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options));
}
+
var snapshotArray = array.createSnapshot(options);
+
if (adapter.shouldReloadAll(this, snapshotArray)) {
return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options));
}
- if (adapter.shouldBackgroundReloadAll(this, snapshotArray)) {
+
+ if (options.backgroundReload === false) {
+ return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array));
+ }
+
+ if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) {
(0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options);
}
+
return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array));
},
/**
@method didUpdateAll
@@ -9419,19 +9552,14 @@
} else {
payload = inputPayload;
serializer = this.serializerFor(modelName);
}
- if (false) {
- return this._adapterRun(function () {
- return serializer.pushPayload(_this3, payload);
- });
- } else {
- this._adapterRun(function () {
- return serializer.pushPayload(_this3, payload);
- });
- }
+
+ this._adapterRun(function () {
+ return serializer.pushPayload(_this3, payload);
+ });
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
@@ -9611,46 +9739,10 @@
this.unloadAll();
}
});
- if (true) {
-
- Store.reopen({
- /**
- Get the reference for the specified record.
- Example
- ```javascript
- var userRef = store.getReference('user', 1);
- // check if the user is loaded
- var isLoaded = userRef.value() !== null;
- // get the record of the reference (null if not yet available)
- var user = userRef.value();
- // get the identifier of the reference
- if (userRef.remoteType() === "id") {
- var id = userRef.id();
- }
- // load user (via store.find)
- userRef.load().then(...)
- // or trigger a reload
- userRef.reload().then(...)
- // provide data for reference
- userRef.push({ id: 1, username: "@user" }).then(function(user) {
- userRef.value() === user;
- });
- ```
- @method getReference
- @param {String} type
- @param {String|Integer} id
- @return {RecordReference}
- */
- getReference: function (type, id) {
- return this._internalModelForId(type, id).recordReference;
- }
- });
- }
-
function deserializeRecordId(store, key, relationship, id) {
if (isNone(id)) {
return;
}
@@ -10236,16 +10328,12 @@
*/
exports.default = _emberDataTransform.default.extend({
deserialize: function (serialized, options) {
var type = typeof serialized;
- if (true) {
- if (false) {
- if (isNone(serialized) && options.allowNull === true) {
- return null;
- }
- }
+ if (isNone(serialized) && options.allowNull === true) {
+ return null;
}
if (type === "boolean") {
return serialized;
} else if (type === "string") {
@@ -10256,29 +10344,25 @@
return false;
}
},
serialize: function (deserialized, options) {
- if (true) {
- if (false) {
- if (isNone(deserialized) && options.allowNull === true) {
- return null;
- }
- }
+ if (isNone(deserialized) && options.allowNull === true) {
+ return null;
}
return Boolean(deserialized);
}
});
});
-define("ember-data/-private/transforms/date", ["exports", "ember", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _ember, _emberDataPrivateExtDate, _emberDataTransform) {
+define("ember-data/-private/transforms/date", ["exports", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _emberDataPrivateExtDate, _emberDataTransform) {
exports.default = _emberDataTransform.default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === "string") {
- return new Date(_ember.default.Date.parse(serialized));
+ return new Date((0, _emberDataPrivateExtDate.parseDate)(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is null return null
// if the value is not present in the data return undefined
@@ -10571,12 +10655,12 @@
defaultSerializer: '-default',
/**
The `findRecord()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `findRecord()` being called, you
- should query your persistence layer for a record with the given ID. The `findRecord`
- method should return a promise that will resolve to a JavaScript object that will be
+ should query your persistence layer for a record with the given ID. The `findRecord`
+ method should return a promise that will resolve to a JavaScript object that will be
normalized by the serializer.
Here is an example `findRecord` implementation:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
@@ -11062,13 +11146,10 @@
detail: message
}];
}
var extendedErrorsEnabled = false;
- if (false) {
- extendedErrorsEnabled = true;
- }
function extendFn(ErrorClass) {
return function () {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
@@ -11351,16 +11432,11 @@
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, type, ids, snapshots) {
- if (false) {
- return this._super.apply(this, arguments);
- } else {
- var url = this.buildURL(type.modelName, ids, snapshots, 'findMany');
- return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } });
- }
+ return this._super.apply(this, arguments);
},
/**
@method pathForType
@param {String} modelName
@@ -11378,85 +11454,70 @@
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, type, snapshot) {
- if (false) {
- return this._super.apply(this, arguments);
- } else {
- var data = {};
- var serializer = store.serializerFor(type.modelName);
-
- serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
-
- var id = snapshot.id;
- var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
-
- return this.ajax(url, 'PATCH', { data: data });
- }
+ return this._super.apply(this, arguments);
}
});
- if (false) {
+ JSONAPIAdapter.reopen({
- JSONAPIAdapter.reopen({
+ methodForRequest: function (params) {
+ if (params.requestType === 'updateRecord') {
+ return 'PATCH';
+ }
- methodForRequest: function (params) {
- if (params.requestType === 'updateRecord') {
- return 'PATCH';
- }
+ return this._super.apply(this, arguments);
+ },
- return this._super.apply(this, arguments);
- },
+ dataForRequest: function (params) {
+ var requestType = params.requestType;
+ var ids = params.ids;
- dataForRequest: function (params) {
- var requestType = params.requestType;
- var ids = params.ids;
+ if (requestType === 'findMany') {
+ return {
+ filter: { id: ids.join(',') }
+ };
+ }
- if (requestType === 'findMany') {
- return {
- filter: { id: ids.join(',') }
- };
- }
+ if (requestType === 'updateRecord') {
+ var store = params.store;
+ var type = params.type;
+ var snapshot = params.snapshot;
- if (requestType === 'updateRecord') {
- var store = params.store;
- var type = params.type;
- var snapshot = params.snapshot;
+ var data = {};
+ var serializer = store.serializerFor(type.modelName);
- var data = {};
- var serializer = store.serializerFor(type.modelName);
+ serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
- serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
+ return data;
+ }
- return data;
- }
+ return this._super.apply(this, arguments);
+ },
- return this._super.apply(this, arguments);
- },
+ headersForRequest: function () {
+ var headers = this._super.apply(this, arguments) || {};
- headersForRequest: function () {
- var headers = this._super.apply(this, arguments) || {};
+ headers['Accept'] = 'application/vnd.api+json';
- headers['Accept'] = 'application/vnd.api+json';
+ return headers;
+ },
- return headers;
- },
+ _requestToJQueryAjaxHash: function () {
+ var hash = this._super.apply(this, arguments);
- _requestToJQueryAjaxHash: function () {
- var hash = this._super.apply(this, arguments);
-
- if (hash.contentType) {
- hash.contentType = 'application/vnd.api+json';
- }
-
- return hash;
+ if (hash.contentType) {
+ hash.contentType = 'application/vnd.api+json';
}
- });
- }
+ return hash;
+ }
+ });
+
exports.default = JSONAPIAdapter;
});
/**
@module ember-data
*/
@@ -11819,23 +11880,16 @@
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
findRecord: function (store, type, id, snapshot) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, id: id, snapshot: snapshot,
- requestType: 'findRecord'
- });
+ var request = this._requestFor({
+ store: store, type: type, id: id, snapshot: snapshot,
+ requestType: 'findRecord'
+ });
- return this._makeRequest(request);
- } else {
- var url = this.buildURL(type.modelName, id, snapshot, 'findRecord');
- var query = this.buildQuery(snapshot);
-
- return this.ajax(url, 'GET', { data: query });
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
@@ -11849,27 +11903,17 @@
@return {Promise} promise
*/
findAll: function (store, type, sinceToken, snapshotRecordArray) {
var query = this.buildQuery(snapshotRecordArray);
- if (false) {
- var request = this._requestFor({
- store: store, type: type, sinceToken: sinceToken, query: query,
- snapshots: snapshotRecordArray,
- requestType: 'findAll'
- });
+ var request = this._requestFor({
+ store: store, type: type, sinceToken: sinceToken, query: query,
+ snapshots: snapshotRecordArray,
+ requestType: 'findAll'
+ });
- return this._makeRequest(request);
- } else {
- var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll');
-
- if (sinceToken) {
- query.since = sinceToken;
- }
-
- return this.ajax(url, 'GET', { data: query });
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
@@ -11883,26 +11927,16 @@
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
query: function (store, type, query) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, query: query,
- requestType: 'query'
- });
+ var request = this._requestFor({
+ store: store, type: type, query: query,
+ requestType: 'query'
+ });
- return this._makeRequest(request);
- } else {
- var url = this.buildURL(type.modelName, null, null, 'query', query);
-
- if (this.sortQueryParams) {
- query = this.sortQueryParams(query);
- }
-
- return this.ajax(url, 'GET', { data: query });
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch a JSON object for
the record that matches a particular query.
@@ -11916,26 +11950,16 @@
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
queryRecord: function (store, type, query) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, query: query,
- requestType: 'queryRecord'
- });
+ var request = this._requestFor({
+ store: store, type: type, query: query,
+ requestType: 'queryRecord'
+ });
- return this._makeRequest(request);
- } else {
- var url = this.buildURL(type.modelName, null, null, 'queryRecord', query);
-
- if (this.sortQueryParams) {
- query = this.sortQueryParams(query);
- }
-
- return this.ajax(url, 'GET', { data: query });
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
@@ -11961,21 +11985,16 @@
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, type, ids, snapshots) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, ids: ids, snapshots: snapshots,
- requestType: 'findMany'
- });
+ var request = this._requestFor({
+ store: store, type: type, ids: ids, snapshots: snapshots,
+ requestType: 'findMany'
+ });
- return this._makeRequest(request);
- } else {
- var url = this.buildURL(type.modelName, ids, snapshots, 'findMany');
- return this.ajax(url, 'GET', { data: { ids: ids } });
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
@@ -12001,25 +12020,16 @@
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findHasMany: function (store, snapshot, url, relationship) {
- if (false) {
- var request = this._requestFor({
- store: store, snapshot: snapshot, url: url, relationship: relationship,
- requestType: 'findHasMany'
- });
+ var request = this._requestFor({
+ store: store, snapshot: snapshot, url: url, relationship: relationship,
+ requestType: 'findHasMany'
+ });
- return this._makeRequest(request);
- } else {
- var id = snapshot.id;
- var type = snapshot.modelName;
-
- url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany'));
-
- return this.ajax(url, 'GET');
- }
+ return this._makeRequest(request);
},
/**
Called by the store in order to fetch the JSON for the unloaded record in a
belongs-to relationship that was originally specified as a URL (inside of
@@ -12045,24 +12055,16 @@
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findBelongsTo: function (store, snapshot, url, relationship) {
- if (false) {
- var request = this._requestFor({
- store: store, snapshot: snapshot, url: url, relationship: relationship,
- requestType: 'findBelongsTo'
- });
+ var request = this._requestFor({
+ store: store, snapshot: snapshot, url: url, relationship: relationship,
+ requestType: 'findBelongsTo'
+ });
- return this._makeRequest(request);
- } else {
- var id = snapshot.id;
- var type = snapshot.modelName;
-
- url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo'));
- return this.ajax(url, 'GET');
- }
+ return this._makeRequest(request);
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
@@ -12075,26 +12077,16 @@
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function (store, type, snapshot) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, snapshot: snapshot,
- requestType: 'createRecord'
- });
+ var request = this._requestFor({
+ store: store, type: type, snapshot: snapshot,
+ requestType: 'createRecord'
+ });
- return this._makeRequest(request);
- } else {
- var data = {};
- var serializer = store.serializerFor(type.modelName);
- var url = this.buildURL(type.modelName, null, snapshot, 'createRecord');
-
- serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
-
- return this.ajax(url, "POST", { data: data });
- }
+ return this._makeRequest(request);
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
@@ -12107,28 +12099,16 @@
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, type, snapshot) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, snapshot: snapshot,
- requestType: 'updateRecord'
- });
+ var request = this._requestFor({
+ store: store, type: type, snapshot: snapshot,
+ requestType: 'updateRecord'
+ });
- return this._makeRequest(request);
- } else {
- var data = {};
- var serializer = store.serializerFor(type.modelName);
-
- serializer.serializeIntoHash(data, type, snapshot);
-
- var id = snapshot.id;
- var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
-
- return this.ajax(url, "PUT", { data: data });
- }
+ return this._makeRequest(request);
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@@ -12137,32 +12117,30 @@
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function (store, type, snapshot) {
- if (false) {
- var request = this._requestFor({
- store: store, type: type, snapshot: snapshot,
- requestType: 'deleteRecord'
- });
+ var request = this._requestFor({
+ store: store, type: type, snapshot: snapshot,
+ requestType: 'deleteRecord'
+ });
- return this._makeRequest(request);
- } else {
- var id = snapshot.id;
-
- return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE");
- }
+ return this._makeRequest(request);
},
_stripIDFromURL: function (store, snapshot) {
var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot);
var expandedURL = url.split('/');
- //Case when the url is of the format ...something/:id
+ // Case when the url is of the format ...something/:id
+ // We are decodeURIComponent-ing the lastSegment because if it represents
+ // the id, it has been encodeURIComponent-ified within `buildURL`. If we
+ // don't do this, then records with id having special characters are not
+ // coalesced correctly (see GH #4190 for the reported bug)
var lastSegment = expandedURL[expandedURL.length - 1];
var id = snapshot.id;
- if (lastSegment === id) {
+ if (decodeURIComponent(lastSegment) === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (endsWith(lastSegment, '?id=' + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
@@ -12268,27 +12246,10 @@
}
var errors = this.normalizeErrorResponse(status, headers, payload);
var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData);
- if (false) {
- switch (status) {
- case 401:
- return new _emberDataAdaptersErrors.UnauthorizedError(errors, detailedMessage);
- case 403:
- return new _emberDataAdaptersErrors.ForbiddenError(errors, detailedMessage);
- case 404:
- return new _emberDataAdaptersErrors.NotFoundError(errors, detailedMessage);
- case 409:
- return new _emberDataAdaptersErrors.ConflictError(errors, detailedMessage);
- default:
- if (status >= 500) {
- return new _emberDataAdaptersErrors.ServerError(errors, detailedMessage);
- }
- }
- }
-
return new _emberDataAdaptersErrors.AdapterError(errors, detailedMessage);
},
/**
Default `handleResponse` implementation uses this hook to decide if the
@@ -12429,11 +12390,13 @@
parseErrorResponse: function (responseText) {
var json = responseText;
try {
json = _ember.default.$.parseJSON(responseText);
- } catch (e) {}
+ } catch (e) {
+ // ignored
+ }
return json;
},
/**
@@ -12484,276 +12447,273 @@
},
buildQuery: function (snapshot) {
var query = {};
- if (true) {
- if (snapshot) {
- var include = snapshot.include;
+ if (snapshot) {
+ var include = snapshot.include;
- if (include) {
- query.include = include;
- }
+ if (include) {
+ query.include = include;
}
}
return query;
}
});
- if (false) {
+ RESTAdapter.reopen({
- RESTAdapter.reopen({
+ /**
+ * Get the data (body or query params) for a request.
+ *
+ * @public
+ * @method dataForRequest
+ * @param {Object} params
+ * @return {Object} data
+ */
+ dataForRequest: function (params) {
+ var store = params.store;
+ var type = params.type;
+ var snapshot = params.snapshot;
+ var requestType = params.requestType;
+ var query = params.query;
- /**
- * Get the data (body or query params) for a request.
- *
- * @public
- * @method dataForRequest
- * @param {Object} params
- * @return {Object} data
- */
- dataForRequest: function (params) {
- var store = params.store;
- var type = params.type;
- var snapshot = params.snapshot;
- var requestType = params.requestType;
- var query = params.query;
+ // type is not passed to findBelongsTo and findHasMany
+ type = type || snapshot && snapshot.type;
- // type is not passed to findBelongsTo and findHasMany
- type = type || snapshot && snapshot.type;
+ var serializer = store.serializerFor(type.modelName);
+ var data = {};
- var serializer = store.serializerFor(type.modelName);
- var data = {};
+ switch (requestType) {
+ case 'createRecord':
+ serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
+ break;
- switch (requestType) {
- case 'createRecord':
- serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
- break;
+ case 'updateRecord':
+ serializer.serializeIntoHash(data, type, snapshot);
+ break;
- case 'updateRecord':
- serializer.serializeIntoHash(data, type, snapshot);
- break;
+ case 'findRecord':
+ data = this.buildQuery(snapshot);
+ break;
- case 'findRecord':
- data = this.buildQuery(snapshot);
- break;
+ case 'findAll':
+ if (params.sinceToken) {
+ query = query || {};
+ query.since = params.sinceToken;
+ }
+ data = query;
+ break;
- case 'findAll':
- if (params.sinceToken) {
- query = query || {};
- query.since = params.sinceToken;
- }
- data = query;
- break;
+ case 'query':
+ case 'queryRecord':
+ if (this.sortQueryParams) {
+ query = this.sortQueryParams(query);
+ }
+ data = query;
+ break;
- case 'query':
- case 'queryRecord':
- if (this.sortQueryParams) {
- query = this.sortQueryParams(query);
- }
- data = query;
- break;
+ case 'findMany':
+ data = { ids: params.ids };
+ break;
- case 'findMany':
- data = { ids: params.ids };
- break;
+ default:
+ data = undefined;
+ break;
+ }
- default:
- data = undefined;
- break;
- }
+ return data;
+ },
- return data;
- },
+ /**
+ * Get the HTTP method for a request.
+ *
+ * @public
+ * @method methodForRequest
+ * @param {Object} params
+ * @return {String} HTTP method
+ */
+ methodForRequest: function (params) {
+ var requestType = params.requestType;
- /**
- * Get the HTTP method for a request.
- *
- * @public
- * @method methodForRequest
- * @param {Object} params
- * @return {String} HTTP method
- */
- methodForRequest: function (params) {
- var requestType = params.requestType;
+ switch (requestType) {
+ case 'createRecord':
+ return 'POST';
+ case 'updateRecord':
+ return 'PUT';
+ case 'deleteRecord':
+ return 'DELETE';
+ }
- switch (requestType) {
- case 'createRecord':
- return 'POST';
- case 'updateRecord':
- return 'PUT';
- case 'deleteRecord':
- return 'DELETE';
- }
+ return 'GET';
+ },
- return 'GET';
- },
+ /**
+ * Get the URL for a request.
+ *
+ * @public
+ * @method urlForRequest
+ * @param {Object} params
+ * @return {String} URL
+ */
+ urlForRequest: function (params) {
+ var type = params.type;
+ var id = params.id;
+ var ids = params.ids;
+ var snapshot = params.snapshot;
+ var snapshots = params.snapshots;
+ var requestType = params.requestType;
+ var query = params.query;
- /**
- * Get the URL for a request.
- *
- * @public
- * @method urlForRequest
- * @param {Object} params
- * @return {String} URL
- */
- urlForRequest: function (params) {
- var type = params.type;
- var id = params.id;
- var ids = params.ids;
- var snapshot = params.snapshot;
- var snapshots = params.snapshots;
- var requestType = params.requestType;
- var query = params.query;
+ // type and id are not passed from updateRecord and deleteRecord, hence they
+ // are defined if not set
+ type = type || snapshot && snapshot.type;
+ id = id || snapshot && snapshot.id;
- // type and id are not passed from updateRecord and deleteRecord, hence they
- // are defined if not set
- type = type || snapshot && snapshot.type;
- id = id || snapshot && snapshot.id;
+ switch (requestType) {
+ case 'findAll':
+ return this.buildURL(type.modelName, null, snapshots, requestType);
- switch (requestType) {
- case 'findAll':
- return this.buildURL(type.modelName, null, snapshots, requestType);
+ case 'query':
+ case 'queryRecord':
+ return this.buildURL(type.modelName, null, null, requestType, query);
- case 'query':
- case 'queryRecord':
- return this.buildURL(type.modelName, null, null, requestType, query);
+ case 'findMany':
+ return this.buildURL(type.modelName, ids, snapshots, requestType);
- case 'findMany':
- return this.buildURL(type.modelName, ids, snapshots, requestType);
-
- case 'findHasMany':
- case 'findBelongsTo':
+ case 'findHasMany':
+ case 'findBelongsTo':
+ {
var url = this.buildURL(type.modelName, id, snapshot, requestType);
return this.urlPrefix(params.url, url);
- }
+ }
+ }
- return this.buildURL(type.modelName, id, snapshot, requestType, query);
- },
+ return this.buildURL(type.modelName, id, snapshot, requestType, query);
+ },
- /**
- * Get the headers for a request.
- *
- * By default the value of the `headers` property of the adapter is
- * returned.
- *
- * @public
- * @method headersForRequest
- * @param {Object} params
- * @return {Object} headers
- */
- headersForRequest: function (params) {
- return this.get('headers');
- },
+ /**
+ * Get the headers for a request.
+ *
+ * By default the value of the `headers` property of the adapter is
+ * returned.
+ *
+ * @public
+ * @method headersForRequest
+ * @param {Object} params
+ * @return {Object} headers
+ */
+ headersForRequest: function (params) {
+ return this.get('headers');
+ },
- /**
- * Get an object which contains all properties for a request which should
- * be made.
- *
- * @private
- * @method _requestFor
- * @param {Object} params
- * @return {Object} request object
- */
- _requestFor: function (params) {
- var method = this.methodForRequest(params);
- var url = this.urlForRequest(params);
- var headers = this.headersForRequest(params);
- var data = this.dataForRequest(params);
+ /**
+ * Get an object which contains all properties for a request which should
+ * be made.
+ *
+ * @private
+ * @method _requestFor
+ * @param {Object} params
+ * @return {Object} request object
+ */
+ _requestFor: function (params) {
+ var method = this.methodForRequest(params);
+ var url = this.urlForRequest(params);
+ var headers = this.headersForRequest(params);
+ var data = this.dataForRequest(params);
- return { method: method, url: url, headers: headers, data: data };
- },
+ return { method: method, url: url, headers: headers, data: data };
+ },
- /**
- * Convert a request object into a hash which can be passed to `jQuery.ajax`.
- *
- * @private
- * @method _requestToJQueryAjaxHash
- * @param {Object} request
- * @return {Object} jQuery ajax hash
- */
- _requestToJQueryAjaxHash: function (request) {
- var hash = {};
+ /**
+ * Convert a request object into a hash which can be passed to `jQuery.ajax`.
+ *
+ * @private
+ * @method _requestToJQueryAjaxHash
+ * @param {Object} request
+ * @return {Object} jQuery ajax hash
+ */
+ _requestToJQueryAjaxHash: function (request) {
+ var hash = {};
- hash.type = request.method;
- hash.url = request.url;
- hash.dataType = 'json';
- hash.context = this;
+ hash.type = request.method;
+ hash.url = request.url;
+ hash.dataType = 'json';
+ hash.context = this;
- if (request.data) {
- if (request.type !== 'GET') {
- hash.contentType = 'application/json; charset=utf-8';
- hash.data = JSON.stringify(request.data);
- } else {
- hash.data = request.data;
- }
+ if (request.data) {
+ if (request.type !== 'GET') {
+ hash.contentType = 'application/json; charset=utf-8';
+ hash.data = JSON.stringify(request.data);
+ } else {
+ hash.data = request.data;
}
+ }
- var headers = request.headers;
- if (headers !== undefined) {
- hash.beforeSend = function (xhr) {
- Object.keys(headers).forEach(function (key) {
- return xhr.setRequestHeader(key, headers[key]);
- });
- };
- }
+ var headers = request.headers;
+ if (headers !== undefined) {
+ hash.beforeSend = function (xhr) {
+ Object.keys(headers).forEach(function (key) {
+ return xhr.setRequestHeader(key, headers[key]);
+ });
+ };
+ }
- return hash;
- },
+ return hash;
+ },
- /**
- * Make a request using `jQuery.ajax`.
- *
- * @private
- * @method _makeRequest
- * @param {Object} request
- * @return {Promise} promise
- */
- _makeRequest: function (request) {
- var adapter = this;
- var hash = this._requestToJQueryAjaxHash(request);
+ /**
+ * Make a request using `jQuery.ajax`.
+ *
+ * @private
+ * @method _makeRequest
+ * @param {Object} request
+ * @return {Promise} promise
+ */
+ _makeRequest: function (request) {
+ var adapter = this;
+ var hash = this._requestToJQueryAjaxHash(request);
- var method = request.method;
- var url = request.url;
+ var method = request.method;
+ var url = request.url;
- var requestData = { method: method, url: url };
+ var requestData = { method: method, url: url };
- return new _ember.default.RSVP.Promise(function (resolve, reject) {
+ return new _ember.default.RSVP.Promise(function (resolve, reject) {
- hash.success = function (payload, textStatus, jqXHR) {
- var response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), payload, requestData);
+ hash.success = function (payload, textStatus, jqXHR) {
+ var response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), payload, requestData);
- if (response instanceof _emberDataAdaptersErrors.AdapterError) {
- _ember.default.run.join(null, reject, response);
- } else {
- _ember.default.run.join(null, resolve, response);
- }
- };
+ if (response instanceof _emberDataAdaptersErrors.AdapterError) {
+ _ember.default.run.join(null, reject, response);
+ } else {
+ _ember.default.run.join(null, resolve, response);
+ }
+ };
- hash.error = function (jqXHR, textStatus, errorThrown) {
+ hash.error = function (jqXHR, textStatus, errorThrown) {
- var error = undefined;
+ var error = undefined;
- if (errorThrown instanceof Error) {
- error = errorThrown;
- } else if (textStatus === 'timeout') {
- error = new _emberDataAdaptersErrors.TimeoutError();
- } else if (textStatus === 'abort') {
- error = new _emberDataAdaptersErrors.AbortError();
- } else {
- error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || errorThrown, requestData);
- }
+ if (errorThrown instanceof Error) {
+ error = errorThrown;
+ } else if (textStatus === 'timeout') {
+ error = new _emberDataAdaptersErrors.TimeoutError();
+ } else if (textStatus === 'abort') {
+ error = new _emberDataAdaptersErrors.AbortError();
+ } else {
+ error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || errorThrown, requestData);
+ }
- _ember.default.run.join(null, reject, error);
- };
+ _ember.default.run.join(null, reject, error);
+ };
- adapter._ajaxRequest(hash);
- }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url);
- }
- });
- }
+ adapter._ajaxRequest(hash);
+ }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url);
+ }
+ });
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== 'function') {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
@@ -12839,10 +12799,38 @@
return {};
}})
});
```
+ The `options` hash is passed as second argument to a transforms'
+ `serialize` and `deserialize` method. This allows to configure a
+ transformation and adapt the corresponding value, based on the config:
+
+ ```app/models/post.js
+ export default DS.Model.extend({
+ text: DS.attr('text', {
+ uppercase: true
+ })
+ });
+ ```
+
+ ```app/transforms/text.js
+ export default DS.Transform.extend({
+ serialize: function(value, options) {
+ if (options.uppercase) {
+ return value.toUpperCase();
+ }
+
+ return value;
+ },
+
+ deserialize: function(value) {
+ return value;
+ }
+ })
+ ```
+
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@@ -12898,44 +12886,13 @@
return value;
}
}).meta(meta);
}
-
- // TODO add to documentation of `attr` function above, once this feature is added
- // /**
- // * The `options` hash is passed as second argument to a transforms'
- // * `serialize` and `deserialize` method. This allows to configure a
- // * transformation and adapt the corresponding value, based on the config:
- // *
- // * ```app/models/post.js
- // * export default DS.Model.extend({
- // * text: DS.attr('text', {
- // * uppercase: true
- // * })
- // * });
- // * ```
- // *
- // * ```app/transforms/text.js
- // * export default DS.Transform.extend({
- // * serialize: function(value, options) {
- // * if (options.uppercase) {
- // * return value.toUpperCase();
- // * }
- // *
- // * return value;
- // * },
- // *
- // * deserialize: function(value) {
- // * return value;
- // * }
- // * })
- // * ```
- // *
- // */
});
-define("ember-data", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/features", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/container-proxy", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemContainerProxy, _emberDataPrivateSystemRelationshipsStateRelationship) {
+define("ember-data", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/features", "ember-data/-private/global", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/container-proxy", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures, _emberDataPrivateGlobal, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemContainerProxy, _emberDataPrivateSystemRelationshipsStateRelationship) {
+
/**
Ember Data
@module ember-data
@main ember-data
*/
@@ -12963,18 +12920,10 @@
_emberDataPrivateCore.default.AdapterError = _emberDataAdaptersErrors.AdapterError;
_emberDataPrivateCore.default.InvalidError = _emberDataAdaptersErrors.InvalidError;
_emberDataPrivateCore.default.TimeoutError = _emberDataAdaptersErrors.TimeoutError;
_emberDataPrivateCore.default.AbortError = _emberDataAdaptersErrors.AbortError;
- if (false) {
- _emberDataPrivateCore.default.UnauthorizedError = _emberDataAdaptersErrors.UnauthorizedError;
- _emberDataPrivateCore.default.ForbiddenError = _emberDataAdaptersErrors.ForbiddenError;
- _emberDataPrivateCore.default.NotFoundError = _emberDataAdaptersErrors.NotFoundError;
- _emberDataPrivateCore.default.ConflictError = _emberDataAdaptersErrors.ConflictError;
- _emberDataPrivateCore.default.ServerError = _emberDataAdaptersErrors.ServerError;
- }
-
_emberDataPrivateCore.default.errorsHashToArray = _emberDataAdaptersErrors.errorsHashToArray;
_emberDataPrivateCore.default.errorsArrayToHash = _emberDataAdaptersErrors.errorsArrayToHash;
_emberDataPrivateCore.default.Serializer = _emberDataSerializer.default;
@@ -13019,12 +12968,18 @@
writable: false,
configurable: false,
value: _emberDataPrivateSystemNormalizeModelName.default
});
- _ember.default.lookup.DS = _emberDataPrivateCore.default;
+ Object.defineProperty(_emberDataPrivateGlobal.default, 'DS', {
+ configurable: true,
+ get: function () {
+ return _emberDataPrivateCore.default;
+ }
+ });
+
exports.default = _emberDataPrivateCore.default;
});
define("ember-data/model", ["exports", "ember-data/-private/system/model"], function (exports, _emberDataPrivateSystemModel) {
exports.default = _emberDataPrivateSystemModel.default;
});
@@ -13461,14 +13416,12 @@
var serializedKey = this.keyForRelationship(attr, relationship.kind, 'serialize');
json[serializedKey] = snapshot.hasMany(attr, { ids: true });
} else if (this.hasSerializeRecordsOption(attr)) {
this._serializeEmbeddedHasMany(snapshot, json, relationship);
} else {
- if (true) {
- if (this.hasSerializeIdsAndTypesOption(attr)) {
- this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
- }
+ if (this.hasSerializeIdsAndTypesOption(attr)) {
+ this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
}
}
},
/**
@@ -13828,10 +13781,11 @@
@private
*/
_normalizeRelationshipDataHelper: function (relationshipDataHash) {
var type = this.modelNameFromPayloadKey(relationshipDataHash.type);
relationshipDataHash.type = type;
+
return relationshipDataHash;
},
/**
@method _normalizeResourceHelper
@@ -13839,12 +13793,16 @@
@return {Object}
@private
*/
_normalizeResourceHelper: function (resourceHash) {
- var modelName = this.modelNameFromPayloadKey(resourceHash.type);
+ var modelName = undefined,
+ usedLookup = undefined;
+ modelName = this.modelNameFromPayloadKey(resourceHash.type);
+ usedLookup = 'modelNameFromPayloadKey';
+
if (!this.store._hasModelFor(modelName)) {
return null;
}
var modelClass = this.store.modelFor(modelName);
@@ -13862,15 +13820,12 @@
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function (store, payload) {
var normalizedPayload = this._normalizeDocumentHelper(payload);
- if (false) {
- return store.push(normalizedPayload);
- } else {
- store.push(normalizedPayload);
- }
+
+ store.push(normalizedPayload);
},
/**
@method _normalizeResponse
@param {DS.Store} store
@@ -13905,11 +13860,11 @@
var attributes = {};
if (resourceHash.attributes) {
modelClass.eachAttribute(function (key) {
var attributeKey = _this.keyForAttribute(key, 'deserialize');
- if (resourceHash.attributes.hasOwnProperty(attributeKey)) {
+ if (resourceHash.attributes[attributeKey] !== undefined) {
attributes[key] = resourceHash.attributes[attributeKey];
}
});
}
@@ -13953,11 +13908,11 @@
var relationships = {};
if (resourceHash.relationships) {
modelClass.eachRelationship(function (key, relationshipMeta) {
var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
- if (resourceHash.relationships.hasOwnProperty(relationshipKey)) {
+ if (resourceHash.relationships[relationshipKey] !== undefined) {
var relationshipHash = resourceHash.relationships[relationshipKey];
relationships[key] = _this2.extractRelationship(relationshipHash);
}
});
@@ -13980,19 +13935,21 @@
/**
@method modelNameFromPayloadKey
@param {String} key
@return {String} the model's modelName
*/
+ // TODO @deprecated Use modelNameFromPayloadType instead
modelNameFromPayloadKey: function (key) {
return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(key));
},
/**
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
+ // TODO @deprecated Use payloadTypeFromModelName instead
payloadKeyFromModelName: function (modelName) {
return (0, _emberInflector.pluralize)(modelName);
},
/**
@@ -14079,11 +14036,16 @@
@param {Object} options
@return {Object} json
*/
serialize: function (snapshot, options) {
var data = this._super.apply(this, arguments);
- data.type = this.payloadKeyFromModelName(snapshot.modelName);
+
+ var payloadType = undefined;
+
+ payloadType = this.payloadKeyFromModelName(snapshot.modelName);
+
+ data.type = payloadType;
return { data: data };
},
/**
@method serializeAttribute
@@ -14099,11 +14061,11 @@
json.attributes = json.attributes || {};
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
- value = transform.serialize(value, attribute.options);
+ value = transform.serialize(value);
}
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key) {
@@ -14134,12 +14096,16 @@
payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize');
}
var data = null;
if (belongsTo) {
+ var payloadType = undefined;
+
+ payloadType = this.payloadKeyFromModelName(belongsTo.modelName);
+
data = {
- type: this.payloadKeyFromModelName(belongsTo.modelName),
+ type: payloadType,
id: belongsTo.id
};
}
json.relationships[payloadKey] = { data: data };
@@ -14153,12 +14119,13 @@
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
+ var shouldSerializeHasMany = '_shouldSerializeHasMany';
- if (this._shouldSerializeHasMany(snapshot, key, relationship)) {
+ if (this[shouldSerializeHasMany](snapshot, key, relationship)) {
var hasMany = snapshot.hasMany(key);
if (hasMany !== undefined) {
json.relationships = json.relationships || {};
@@ -14169,12 +14136,17 @@
var data = new Array(hasMany.length);
for (var i = 0; i < hasMany.length; i++) {
var item = hasMany[i];
+
+ var payloadType = undefined;
+
+ payloadType = this.payloadKeyFromModelName(item.modelName);
+
data[i] = {
- type: this.payloadKeyFromModelName(item.modelName),
+ type: payloadType,
id: item.id
};
}
json.relationships[payloadKey] = { data: data };
@@ -14186,11 +14158,84 @@
exports.default = JSONAPISerializer;
});
/**
@module ember-data
*/
-define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/adapters/errors', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataAdaptersErrors, _emberDataPrivateFeatures) {
+
+/**
+ `modelNameFromPayloadType` can be used to change the mapping for a DS model
+ name, taken from the value in the payload.
+ Say your API namespaces the type of a model and returns the following
+ payload for the `post` model:
+ ```javascript
+ // GET /api/posts/1
+ {
+ "data": {
+ "id": 1,
+ "type: "api::v1::post"
+ }
+ }
+ ```
+ By overwriting `modelNameFromPayloadType` you can specify that the
+ `posr` model should be used:
+ ```app/serializers/application.js
+ import JSONAPISerializer from "ember-data/serializers/json-api";
+ export default JSONAPISerializer.extend({
+ modelNameFromPayloadType(payloadType) {
+ return payloadType.replace('api::v1::', '');
+ }
+ });
+ ```
+ By default the modelName for a model is its singularized name in dasherized
+ form. Usually, Ember Data can use the correct inflection to do this for
+ you. Most of the time, you won't need to override
+ `modelNameFromPayloadType` for this purpose.
+ Also take a look at
+ [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize
+ how the type of a record should be serialized.
+ @method modelNameFromPayloadType
+ @public
+ @param {String} payloadType type from payload
+ @return {String} modelName
+*/
+
+/**
+ `payloadTypeFromModelName` can be used to change the mapping for the type in
+ the payload, taken from the model name.
+ Say your API namespaces the type of a model and expects the following
+ payload when you update the `post` model:
+ ```javascript
+ // POST /api/posts/1
+ {
+ "data": {
+ "id": 1,
+ "type": "api::v1::post"
+ }
+ }
+ ```
+ By overwriting `payloadTypeFromModelName` you can specify that the
+ namespaces model name for the `post` should be used:
+ ```app/serializers/application.js
+ import JSONAPISerializer from "ember-data/serializers/json-api";
+ export default JSONAPISerializer.extend({
+ payloadTypeFromModelName(modelName) {
+ return "api::v1::" + modelName;
+ }
+ });
+ ```
+ By default the payload type is the pluralized model name. Usually, Ember
+ Data can use the correct inflection to do this for you. Most of the time,
+ you won't need to override `payloadTypeFromModelName` for this purpose.
+ Also take a look at
+ [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize
+ how the model name from should be mapped from the payload.
+ @method payloadTypeFromModelName
+ @public
+ @param {String} modelname modelName from the record
+ @return {String} payloadType
+*/
+define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/features', 'ember-data/adapters/errors'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataPrivateFeatures, _emberDataAdaptersErrors) {
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
var get = _ember.default.get;
var isNone = _ember.default.isNone;
var assign = _ember.default.assign || _ember.default.merge;
@@ -14259,11 +14304,11 @@
@class JSONSerializer
@namespace DS
@extends DS.Serializer
*/
- exports.default = _emberDataSerializer.default.extend({
+ var JSONSerializer = _emberDataSerializer.default.extend({
/**
The `primaryKey` is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
@@ -14347,27 +14392,20 @@
@return {Object} data The transformed data object
*/
applyTransforms: function (typeClass, data) {
var _this = this;
- var attributes = undefined;
- if (true) {
- attributes = get(typeClass, 'attributes');
- }
+ var attributes = get(typeClass, 'attributes');
typeClass.eachTransformedAttribute(function (key, typeClass) {
- if (!(key in data)) {
+ if (data[key] === undefined) {
return;
}
var transform = _this.transformFor(typeClass);
- if (true) {
- var transformMeta = attributes.get(key);
- data[key] = transform.deserialize(data[key], transformMeta.options);
- } else {
- data[key] = transform.deserialize(data[key]);
- }
+ var transformMeta = attributes.get(key);
+ data[key] = transform.deserialize(data[key], transformMeta.options);
});
return data;
},
@@ -14727,11 +14765,11 @@
var attributeKey;
var attributes = {};
modelClass.eachAttribute(function (key) {
attributeKey = _this2.keyForAttribute(key, 'deserialize');
- if (resourceHash.hasOwnProperty(attributeKey)) {
+ if (resourceHash[attributeKey] !== undefined) {
attributes[key] = resourceHash[attributeKey];
}
});
return attributes;
@@ -14802,11 +14840,11 @@
var relationships = {};
modelClass.eachRelationship(function (key, relationshipMeta) {
var relationship = null;
var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
- if (resourceHash.hasOwnProperty(relationshipKey)) {
+ if (resourceHash[relationshipKey] !== undefined) {
var data = null;
var relationshipHash = resourceHash[relationshipKey];
if (relationshipMeta.kind === 'belongsTo') {
if (relationshipMeta.options.polymorphic) {
// extracting a polymorphic belongsTo may need more information
@@ -14828,11 +14866,11 @@
}
relationship = { data: data };
}
var linkKey = _this3.keyForLink(key, relationshipMeta.kind);
- if (resourceHash.links && resourceHash.links.hasOwnProperty(linkKey)) {
+ if (resourceHash.links && resourceHash.links[linkKey] !== undefined) {
var related = resourceHash.links[linkKey];
relationship = relationship || {};
relationship.links = { related: related };
}
@@ -14847,10 +14885,11 @@
/**
@method modelNameFromPayloadKey
@param {String} key
@return {String} the model's modelName
*/
+ // TODO @deprecated Use modelNameFromPayloadType instead
modelNameFromPayloadKey: function (key) {
return (0, _emberDataPrivateSystemNormalizeModelName.default)(key);
},
/**
@@ -14866,11 +14905,11 @@
typeClass.eachAttribute(function (key) {
payloadKey = _this4.keyForAttribute(key, 'deserialize');
if (key === payloadKey) {
return;
}
- if (!hash.hasOwnProperty(payloadKey)) {
+ if (hash[payloadKey] === undefined) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
@@ -14891,11 +14930,11 @@
typeClass.eachRelationship(function (key, relationship) {
payloadKey = _this5.keyForRelationship(key, relationship.kind, 'deserialize');
if (key === payloadKey) {
return;
}
- if (!hash.hasOwnProperty(payloadKey)) {
+ if (hash[payloadKey] === undefined) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
@@ -14913,11 +14952,11 @@
if (attrs) {
for (key in attrs) {
normalizedKey = payloadKey = this._getMappedKey(key, modelClass);
- if (!hash.hasOwnProperty(payloadKey)) {
+ if (hash[payloadKey] === undefined) {
continue;
}
if (get(modelClass, 'attributes').has(key)) {
normalizedKey = this.keyForAttribute(key);
@@ -14991,10 +15030,25 @@
return attrs && attrs[key] && attrs[key].serialize === true;
},
/**
Check if the given hasMany relationship should be serialized
+ @method shouldSerializeHasMany
+ @param {DS.Snapshot} snapshot
+ @param {String} key
+ @param {String} relationshipType
+ @return {boolean} true if the hasMany relationship should be serialized
+ */
+
+ shouldSerializeHasMany: function (snapshot, key, relationship) {
+ if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) {}
+
+ return this._shouldSerializeHasMany(snapshot, key, relationship);
+ },
+
+ /**
+ Check if the given hasMany relationship should be serialized
@method _shouldSerializeHasMany
@private
@param {DS.Snapshot} snapshot
@param {String} key
@param {String} relationshipType
@@ -15203,15 +15257,11 @@
if (this._canSerialize(key)) {
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
- if (true) {
- value = transform.serialize(value, attribute.options);
- } else {
- value = transform.serialize(value);
- }
+ value = transform.serialize(value, attribute.options);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key, snapshot.type);
@@ -15292,12 +15342,13 @@
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
+ var shouldSerializeHasMany = '_shouldSerializeHasMany';
- if (this._shouldSerializeHasMany(snapshot, key, relationship)) {
+ if (this[shouldSerializeHasMany](snapshot, key, relationship)) {
var hasMany = snapshot.hasMany(key, { ids: true });
if (hasMany !== undefined) {
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key, snapshot.type);
@@ -15360,11 +15411,11 @@
@param {DS.Store} store
@param {DS.Model} modelClass
@param {Object} payload
*/
extractMeta: function (store, modelClass, payload) {
- if (payload && payload.hasOwnProperty('meta')) {
+ if (payload && payload['meta'] !== undefined) {
var meta = payload.meta;
delete payload.meta;
return meta;
}
},
@@ -15450,19 +15501,19 @@
this.normalizeUsingDeclaredMapping(typeClass, payload);
typeClass.eachAttribute(function (name) {
var key = _this7.keyForAttribute(name, 'deserialize');
- if (key !== name && payload.hasOwnProperty(key)) {
+ if (key !== name && payload[key] !== undefined) {
payload[name] = payload[key];
delete payload[key];
}
});
typeClass.eachRelationship(function (name) {
var key = _this7.keyForRelationship(name, 'deserialize');
- if (key !== name && payload.hasOwnProperty(key)) {
+ if (key !== name && payload[key] !== undefined) {
payload[name] = payload[key];
delete payload[key];
}
});
}
@@ -15539,11 +15590,20 @@
var transform = (0, _emberDataPrivateUtils.getOwner)(this).lookup('transform:' + attributeType);
return transform;
}
});
+
+ exports.default = JSONSerializer;
});
+
+/**
+ @method modelNameFromPayloadType
+ @public
+ @param {String} type
+ @return {String} the model's modelName
+ */
define("ember-data/serializers/rest", ["exports", "ember", "ember-data/-private/debug", "ember-data/serializers/json", "ember-data/-private/system/normalize-model-name", "ember-inflector", "ember-data/-private/system/coerce-id", "ember-data/-private/utils", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateSystemCoerceId, _emberDataPrivateUtils, _emberDataPrivateFeatures) {
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
var camelize = _ember.default.String.camelize;
@@ -15644,28 +15704,28 @@
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
- or other general-purpose normalizations. You will only need to implement
+ or other general-purpose normalizations. You will only need to implement
`normalize` and manipulate the payload as desired.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalize(model, hash, prop) {
if (prop === 'comments') {
hash.id = hash._id;
- delete hash._id;
+ delete hash._id;
}
return this._super(...arguments);
}
});
```
- On each call to the `normalize` method, the third parameter (`prop`) is always
- one of the keys that were in the original payload or in the result of another
+ On each call to the `normalize` method, the third parameter (`prop`) is always
+ one of the keys that were in the original payload or in the result of another
normalization as `normalizeResponse`.
@method normalize
@param {DS.Model} modelClass
@param {Object} resourceHash
@param {String} prop
@@ -15698,11 +15758,10 @@
};
var modelClass = store.modelFor(modelName);
var serializer = store.serializerFor(modelName);
- /*jshint loopfunc:true*/
_ember.default.makeArray(arrayHash).forEach(function (hash) {
var _normalizePolymorphicRecord = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer);
var data = _normalizePolymorphicRecord.data;
var included = _normalizePolymorphicRecord.included;
@@ -15717,21 +15776,27 @@
return documentHash;
},
_normalizePolymorphicRecord: function (store, hash, prop, primaryModelClass, primarySerializer) {
- var serializer = undefined,
- modelClass = undefined;
+ var serializer = primarySerializer;
+ var modelClass = primaryModelClass;
+
var primaryHasTypeAttribute = (0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(primaryModelClass);
- // Support polymorphic records in async relationships
- if (!primaryHasTypeAttribute && hash.type && store._hasModelFor(this.modelNameFromPayloadKey(hash.type))) {
- serializer = store.serializerFor(this.modelNameFromPayloadKey(hash.type));
- modelClass = store.modelFor(this.modelNameFromPayloadKey(hash.type));
- } else {
- serializer = primarySerializer;
- modelClass = primaryModelClass;
+
+ if (!primaryHasTypeAttribute && hash.type) {
+ // Support polymorphic records in async relationships
+ var modelName = undefined;
+
+ modelName = this.modelNameFromPayloadKey(hash.type);
+
+ if (store._hasModelFor(modelName)) {
+ serializer = store.serializerFor(modelName);
+ modelClass = store.modelFor(modelName);
+ }
}
+
return serializer.normalize(modelClass, hash, prop);
},
/*
@method _normalizeResponse
@@ -15830,11 +15895,10 @@
(_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, _toConsumableArray(included));
}
if (isSingle) {
- /*jshint loopfunc:true*/
data.forEach(function (resource) {
/*
Figures out if this is the primary record or not.
It's either:
@@ -15912,11 +15976,10 @@
continue;
}
var type = store.modelFor(modelName);
var typeSerializer = store.serializerFor(type.modelName);
- /*jshint loopfunc:true*/
_ember.default.makeArray(payload[prop]).forEach(function (hash) {
var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop);
var data = _typeSerializer$normalize.data;
var included = _typeSerializer$normalize.included;
@@ -15928,15 +15991,11 @@
(_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, _toConsumableArray(included));
}
});
}
- if (false) {
- return store.push(documentHash);
- } else {
- store.push(documentHash);
- }
+ store.push(documentHash);
},
/**
This method is used to convert each JSON root key in the payload
into a modelName that it can use to look up the appropriate model for
@@ -16241,11 +16300,12 @@
// corresponding JSON-API representation. The former case is handled within
// the base class JSONSerializer.
var isPolymorphic = relationshipMeta.options.polymorphic;
var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize');
- if (isPolymorphic && resourceHash.hasOwnProperty(typeProperty) && typeof relationshipHash !== 'object') {
+ if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') {
+
var type = this.modelNameFromPayloadKey(resourceHash[typeProperty]);
return {
id: relationshipHash,
type: type
};
@@ -16258,10 +16318,86 @@
exports.default = RESTSerializer;
});
/**
@module ember-data
*/
+
+/**
+ `modelNameFromPayloadType` can be used to change the mapping for a DS model
+ name, taken from the value in the payload.
+ Say your API namespaces the type of a model and returns the following
+ payload for the `post` model, which has a polymorphic `user` relationship:
+ ```javascript
+ // GET /api/posts/1
+ {
+ "post": {
+ "id": 1,
+ "user": 1,
+ "userType: "api::v1::administrator"
+ }
+ }
+ ```
+ By overwriting `modelNameFromPayloadType` you can specify that the
+ `administrator` model should be used:
+ ```app/serializers/application.js
+ import RESTSerializer from "ember-data/serializers/rest";
+ export default RESTSerializer.extend({
+ modelNameFromPayloadType(payloadType) {
+ return payloadType.replace('api::v1::', '');
+ }
+ });
+ ```
+ By default the modelName for a model is its name in dasherized form.
+ Usually, Ember Data can use the correct inflection to do this for you. Most
+ of the time, you won't need to override `modelNameFromPayloadType` for this
+ purpose.
+ Also take a look at
+ [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize
+ how the type of a record should be serialized.
+ @method modelNameFromPayloadType
+ @public
+ @param {String} payloadType type from payload
+ @return {String} modelName
+*/
+
+/**
+ `payloadTypeFromModelName` can be used to change the mapping for the type in
+ the payload, taken from the model name.
+ Say your API namespaces the type of a model and expects the following
+ payload when you update the `post` model, which has a polymorphic `user`
+ relationship:
+ ```javascript
+ // POST /api/posts/1
+ {
+ "post": {
+ "id": 1,
+ "user": 1,
+ "userType": "api::v1::administrator"
+ }
+ }
+ ```
+ By overwriting `payloadTypeFromModelName` you can specify that the
+ namespaces model name for the `administrator` should be used:
+ ```app/serializers/application.js
+ import RESTSerializer from "ember-data/serializers/rest";
+ export default RESTSerializer.extend({
+ payloadTypeFromModelName(modelName) {
+ return "api::v1::" + modelName;
+ }
+ });
+ ```
+ By default the payload type is the camelized model name. Usually, Ember
+ Data can use the correct inflection to do this for you. Most of the time,
+ you won't need to override `payloadTypeFromModelName` for this purpose.
+ Also take a look at
+ [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize
+ how the model name from should be mapped from the payload.
+ @method payloadTypeFromModelName
+ @public
+ @param {String} modelname modelName from the record
+ @return {String} payloadType
+*/
define('ember-data/setup-container', ['exports', 'ember-data/-private/initializers/store', 'ember-data/-private/initializers/transforms', 'ember-data/-private/initializers/store-injections', 'ember-data/-private/initializers/data-adapter'], function (exports, _emberDataPrivateInitializersStore, _emberDataPrivateInitializersTransforms, _emberDataPrivateInitializersStoreInjections, _emberDataPrivateInitializersDataAdapter) {
exports.default = setupContainer;
function setupContainer(application) {
(0, _emberDataPrivateInitializersDataAdapter.default)(application);
@@ -16316,38 +16452,40 @@
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
- serialize: function(deserialized) {
+ serialize: function(deserialized, options) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
+ @param options hash of options passed to `DS.attr`
@return The serialized value
*/
serialize: null,
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
- deserialize: function(serialized) {
+ deserialize: function(serialized, options) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
+ @param options hash of options passed to `DS.attr`
@return The deserialized value
*/
deserialize: null
});
});
define("ember-data/version", ["exports"], function (exports) {
- exports.default = "2.6.2";
+ exports.default = "2.7.0-beta.1";
});
define("ember-inflector", ["exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (exports, _ember, _emberInflectorLibSystem, _emberInflectorLibExtString) {
_emberInflectorLibSystem.Inflector.defaultRules = _emberInflectorLibSystem.defaultRules;
_ember.default.Inflector = _emberInflectorLibSystem.Inflector;
@@ -16738,20 +16876,20 @@
if (isUncountable) {
return word;
}
- for (rule in irregular) {
+ for (rule in this.rules.irregular) {
if (lowercase.match(rule + "$")) {
substitution = irregular[rule];
if (isCamelized && irregular[lastWord]) {
substitution = capitalize(substitution);
rule = capitalize(rule);
}
- return word.replace(new RegExp(rule, 'i'), substitution);
+ return word.replace(rule, substitution);
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i - 1];
@@ -16808,11 +16946,20 @@
});
require("ember-data");
+;(function() {
+ var global = require('ember-data/-private/global').default;
+ var DS = require('ember-data').default;
+ Object.defineProperty(global, 'DS', {
+ get: function() {
+ return DS;
+ }
+ });
})();
+})();
;(function() {
function processEmberDataShims() {
var shims = {
'ember-data': { default: DS },
'ember-data/model': { default: DS.Model },
@@ -16847,9 +16994,11 @@
if (typeof define !== 'undefined' && define && define.petal) {
processEmberDataShims();
}
})();
+/* eslint no-extra-semi: "off" */
+
;(function() {
/* globals Ember */
/* globals DS */
var K = Ember.K;
Ember.onLoad('Ember.Application', function(Application) {