From 0826f81569feb28b4604f53200615febeea704ea Mon Sep 17 00:00:00 2001 From: Chris Thoburn Date: Thu, 4 Oct 2018 15:50:19 -0700 Subject: [PATCH 1/3] remove legacy build --- addon/-legacy-private/attr.js | 137 - addon/-legacy-private/index.js | 56 - addon/-legacy-private/system/many-array.js | 290 -- .../system/model/internal-model.js | 1404 ------- addon/-legacy-private/system/model/model.js | 1994 ---------- addon/-legacy-private/system/model/states.js | 766 ---- .../-legacy-private/system/promise-proxies.js | 162 - .../system/references/belongs-to.js | 440 --- .../system/references/has-many.js | 442 --- .../system/references/reference.js | 10 - .../system/relationships/belongs-to.js | 143 - .../system/relationships/ext.js | 70 - .../system/relationships/has-many.js | 156 - .../relationship-payloads-manager.js | 346 -- .../relationships/relationship-payloads.js | 499 --- .../system/relationships/state/belongs-to.js | 324 -- .../system/relationships/state/create.js | 86 - .../system/relationships/state/has-many.js | 454 --- .../relationships/state/relationship.js | 747 ---- addon/-legacy-private/system/snapshot.js | 409 -- addon/-legacy-private/system/store.js | 3462 ----------------- .../attr.js | 0 .../index.js | 0 .../system/many-array.js | 0 .../system/model/internal-model.js | 0 .../system/model/model.js | 0 .../system/model/record-data.js | 0 .../system/model/states.js | 0 .../system/promise-proxies.js | 0 .../system/references/belongs-to.js | 0 .../system/references/has-many.js | 0 .../system/references/reference.js | 0 .../system/relationships/belongs-to.js | 0 .../system/relationships/ext.js | 0 .../system/relationships/has-many.js | 0 .../system/relationships/state/belongs-to.js | 0 .../system/relationships/state/create.js | 0 .../system/relationships/state/has-many.js | 0 .../relationships/state/relationship.js | 0 .../system/snapshot.js | 0 .../system/store.js | 0 .../system/store/record-data-wrapper.js | 0 index.js | 24 +- lib/cli-flags.js | 17 - tests/dummy/config/environment.js | 5 - tests/helpers/test-in-debug.js | 15 +- 46 files changed, 4 insertions(+), 12454 deletions(-) delete mode 100644 addon/-legacy-private/attr.js delete mode 100644 addon/-legacy-private/index.js delete mode 100644 addon/-legacy-private/system/many-array.js delete mode 100644 addon/-legacy-private/system/model/internal-model.js delete mode 100644 addon/-legacy-private/system/model/model.js delete mode 100644 addon/-legacy-private/system/model/states.js delete mode 100644 addon/-legacy-private/system/promise-proxies.js delete mode 100644 addon/-legacy-private/system/references/belongs-to.js delete mode 100644 addon/-legacy-private/system/references/has-many.js delete mode 100644 addon/-legacy-private/system/references/reference.js delete mode 100644 addon/-legacy-private/system/relationships/belongs-to.js delete mode 100644 addon/-legacy-private/system/relationships/ext.js delete mode 100644 addon/-legacy-private/system/relationships/has-many.js delete mode 100644 addon/-legacy-private/system/relationships/relationship-payloads-manager.js delete mode 100644 addon/-legacy-private/system/relationships/relationship-payloads.js delete mode 100644 addon/-legacy-private/system/relationships/state/belongs-to.js delete mode 100644 addon/-legacy-private/system/relationships/state/create.js delete mode 100755 addon/-legacy-private/system/relationships/state/has-many.js delete mode 100644 addon/-legacy-private/system/relationships/state/relationship.js delete mode 100644 addon/-legacy-private/system/snapshot.js delete mode 100644 addon/-legacy-private/system/store.js rename addon/{-record-data-private => -private}/attr.js (100%) rename addon/{-record-data-private => -private}/index.js (100%) rename addon/{-record-data-private => -private}/system/many-array.js (100%) rename addon/{-record-data-private => -private}/system/model/internal-model.js (100%) rename addon/{-record-data-private => -private}/system/model/model.js (100%) rename addon/{-record-data-private => -private}/system/model/record-data.js (100%) rename addon/{-record-data-private => -private}/system/model/states.js (100%) rename addon/{-record-data-private => -private}/system/promise-proxies.js (100%) rename addon/{-record-data-private => -private}/system/references/belongs-to.js (100%) rename addon/{-record-data-private => -private}/system/references/has-many.js (100%) rename addon/{-record-data-private => -private}/system/references/reference.js (100%) rename addon/{-record-data-private => -private}/system/relationships/belongs-to.js (100%) rename addon/{-record-data-private => -private}/system/relationships/ext.js (100%) rename addon/{-record-data-private => -private}/system/relationships/has-many.js (100%) rename addon/{-record-data-private => -private}/system/relationships/state/belongs-to.js (100%) rename addon/{-record-data-private => -private}/system/relationships/state/create.js (100%) rename addon/{-record-data-private => -private}/system/relationships/state/has-many.js (100%) rename addon/{-record-data-private => -private}/system/relationships/state/relationship.js (100%) rename addon/{-record-data-private => -private}/system/snapshot.js (100%) rename addon/{-record-data-private => -private}/system/store.js (100%) rename addon/{-record-data-private => -private}/system/store/record-data-wrapper.js (100%) diff --git a/addon/-legacy-private/attr.js b/addon/-legacy-private/attr.js deleted file mode 100644 index 47d2947c6e6..00000000000 --- a/addon/-legacy-private/attr.js +++ /dev/null @@ -1,137 +0,0 @@ -import { computed } from '@ember/object'; -import { assert } from '@ember/debug'; - -/** - @module ember-data -*/ - -function getDefaultValue(record, options, key) { - if (typeof options.defaultValue === 'function') { - return options.defaultValue.apply(null, arguments); - } else { - let defaultValue = options.defaultValue; - assert( - `Non primitive defaultValues are not supported because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.`, - typeof defaultValue !== 'object' || defaultValue === null - ); - return defaultValue; - } -} - -function hasValue(record, key) { - return key in record._attributes || key in record._inFlightAttributes || key in record._data; -} - -/** - `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). - By default, attributes are passed through as-is, however you can specify an - optional type to have the value automatically transformed. - Ember Data ships with four basic transform types: `string`, `number`, - `boolean` and `date`. You can define your own transforms by subclassing - [DS.Transform](/api/data/classes/DS.Transform.html). - - Note that you cannot use `attr` to define an attribute of `id`. - - `DS.attr` takes an optional hash as a second parameter, currently - supported options are: - - - `defaultValue`: Pass a string or a function to be called to set the attribute - to a default value if none is supplied. - - Example - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - username: DS.attr('string'), - email: DS.attr('string'), - verified: DS.attr('boolean', { defaultValue: false }) - }); - ``` - - Default value can also be a function. This is useful it you want to return - a new object for each attribute. - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - username: DS.attr('string'), - email: DS.attr('string'), - settings: DS.attr({ - defaultValue() { - 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 - import DS from 'ember-data'; - - export default DS.Model.extend({ - text: DS.attr('text', { - uppercase: true - }) - }); - ``` - - ```app/transforms/text.js - import DS from 'ember-data'; - - export default DS.Transform.extend({ - serialize(value, options) { - if (options.uppercase) { - return value.toUpperCase(); - } - - return value; - }, - - deserialize(value) { - return value; - } - }) - ``` - - @namespace - @method attr - @for DS - @param {String|Object} type the attribute type - @param {Object} options a hash of options - @return {Attribute} -*/ - -export default function attr(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } else { - options = options || {}; - } - - let meta = { - type: type, - isAttribute: true, - options: options, - }; - - return computed({ - get(key) { - let internalModel = this._internalModel; - if (hasValue(internalModel, key)) { - return internalModel.getAttributeValue(key); - } else { - return getDefaultValue(this, options, key); - } - }, - set(key, value) { - return this._internalModel.setDirtyAttribute(key, value); - }, - }).meta(meta); -} diff --git a/addon/-legacy-private/index.js b/addon/-legacy-private/index.js deleted file mode 100644 index a1addb6ec09..00000000000 --- a/addon/-legacy-private/index.js +++ /dev/null @@ -1,56 +0,0 @@ -// public -export { default as Model } from './system/model/model'; -export { default as Errors } from './system/model/errors'; -export { default as Store } from './system/store'; -export { default as DS } from './core'; -export { default as belongsTo } from './system/relationships/belongs-to'; -export { default as hasMany } from './system/relationships/has-many'; -export { default as BuildURLMixin } from './adapters/build-url-mixin'; -export { default as Snapshot } from './system/snapshot'; -export { default as attr } from './attr'; -export { - AdapterError, - InvalidError, - UnauthorizedError, - ForbiddenError, - NotFoundError, - ConflictError, - ServerError, - TimeoutError, - AbortError, - errorsHashToArray, - errorsArrayToHash, -} from './adapters/errors'; - -// maybe public ? -export { default as normalizeModelName } from './system/normalize-model-name'; -export { getOwner, modelHasAttributeOrRelationshipNamedType } from './utils'; -export { default as coerceId } from './system/coerce-id'; -export { default as parseResponseHeaders } from './utils/parse-response-headers'; - -export { default as isEnabled } from './features'; -// `ember-data-model-fragments` relies on `RootState` and `InternalModel` -export { default as RootState } from './system/model/states'; -export { default as InternalModel } from './system/model/internal-model'; - -export { PromiseArray, PromiseObject, PromiseManyArray } from './system/promise-proxies'; - -export { RecordArray, AdapterPopulatedRecordArray } from './system/record-arrays'; - -export { default as ManyArray } from './system/many-array'; -export { default as RecordArrayManager } from './system/record-array-manager'; -export { default as Relationship } from './system/relationships/state/relationship'; - -export { default as Map } from './system/map'; -export { default as MapWithDefault } from './system/map-with-default'; - -// Should be a different Repo ? -export { default as DebugAdapter } from './system/debug/debug-adapter'; - -// Used by tests -export { default as diffArray } from './system/diff-array'; -export { - default as RelationshipPayloadsManager, -} from './system/relationships/relationship-payloads-manager'; -export { default as RelationshipPayloads } from './system/relationships/relationship-payloads'; -export { default as SnapshotRecordArray } from './system/snapshot-record-array'; diff --git a/addon/-legacy-private/system/many-array.js b/addon/-legacy-private/system/many-array.js deleted file mode 100644 index 0812659d8bb..00000000000 --- a/addon/-legacy-private/system/many-array.js +++ /dev/null @@ -1,290 +0,0 @@ -/** - @module ember-data -*/ -import { all } from 'rsvp'; - -import Evented from '@ember/object/evented'; -import MutableArray from '@ember/array/mutable'; -import EmberObject, { get } from '@ember/object'; -import { assert } from '@ember/debug'; -import { PromiseArray } from './promise-proxies'; -import { _objectIsAlive } from './store/common'; -import diffArray from './diff-array'; - -/** - A `ManyArray` is a `MutableArray` that represents the contents of a has-many - relationship. - - The `ManyArray` is instantiated lazily the first time the relationship is - requested. - - ### Inverses - - Often, the relationships in Ember Data applications will have - an inverse. For example, imagine the following models are - defined: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - If you created a new instance of `App.Post` and added - a `App.Comment` record to its `comments` has-many - relationship, you would expect the comment's `post` - property to be set to the post that contained - the has-many. - - We call the record to which a relationship belongs-to the - relationship's _owner_. - - @class ManyArray - @namespace DS - @extends Ember.Object - @uses Ember.MutableArray, Ember.Evented -*/ -export default EmberObject.extend(MutableArray, Evented, { - init() { - this._super(...arguments); - - /** - The loading state of this array - - @property {Boolean} isLoaded - */ - this.isLoaded = this.isLoaded || false; - this.length = 0; - - /** - Used for async `hasMany` arrays - to keep track of when they will resolve. - - @property {Ember.RSVP.Promise} promise - @private - */ - this.promise = null; - - /** - Metadata associated with the request for async hasMany relationships. - - Example - - Given that the server returns the following JSON payload when fetching a - hasMany relationship: - - ```js - { - "comments": [{ - "id": 1, - "comment": "This is the first comment", - }, { - // ... - }], - - "meta": { - "page": 1, - "total": 5 - } - } - ``` - - You can then access the metadata via the `meta` property: - - ```js - post.get('comments').then(function(comments) { - var meta = comments.get('meta'); - - // meta.page => 1 - // meta.total => 5 - }); - ``` - - @property {Object} meta - @public - */ - this.meta = this.meta || null; - - /** - `true` if the relationship is polymorphic, `false` otherwise. - - @property {Boolean} isPolymorphic - @private - */ - this.isPolymorphic = this.isPolymorphic || false; - - /** - The relationship which manages this array. - - @property {ManyRelationship} relationship - @private - */ - this.relationship = this.relationship || null; - - this.currentState = []; - this.flushCanonical(false); - }, - - objectAt(index) { - this.relationship._flushPendingManyArrayUpdates(); - let internalModel = this.currentState[index]; - if (internalModel === undefined) { - return; - } - - return internalModel.getRecord(); - }, - - flushCanonical(isInitialized = true) { - // It’s possible the parent side of the relationship may have been unloaded by this point - if (!_objectIsAlive(this)) { - return; - } - - let toSet = this.relationship.members.list.slice(); - - // diff to find changes - let diff = diffArray(this.currentState, toSet); - - if (diff.firstChangeIndex !== null) { - // it's null if no change found - // we found a change - this.arrayContentWillChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount); - this.set('length', toSet.length); - this.currentState = toSet; - this.arrayContentDidChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount); - if (isInitialized && diff.addedCount > 0) { - //notify only on additions - //TODO only notify if unloaded - this.relationship.notifyHasManyChange(); - } - } - }, - - internalReplace(idx, amt, objects) { - if (!objects) { - objects = []; - } - this.arrayContentWillChange(idx, amt, objects.length); - this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); - this.set('length', this.currentState.length); - this.arrayContentDidChange(idx, amt, objects.length); - }, - - //TODO(Igor) optimize - _removeInternalModels(internalModels) { - for (let i = 0; i < internalModels.length; i++) { - let index = this.currentState.indexOf(internalModels[i]); - this.internalReplace(index, 1); - } - }, - - //TODO(Igor) optimize - _addInternalModels(internalModels, idx) { - if (idx === undefined) { - idx = this.currentState.length; - } - this.internalReplace(idx, 0, internalModels); - }, - - replace(idx, amt, objects) { - let internalModels; - if (amt > 0) { - internalModels = this.currentState.slice(idx, idx + amt); - this.get('relationship').removeInternalModels(internalModels); - } - if (objects) { - this.get('relationship').addInternalModels(objects.map(obj => obj._internalModel), idx); - } - }, - - /** - Reloads all of the records in the manyArray. If the manyArray - holds a relationship that was originally fetched using a links url - Ember Data will revisit the original links url to repopulate the - relationship. - - If the manyArray holds the result of a `store.query()` reload will - re-run the original query. - - Example - - ```javascript - var user = store.peekRecord('user', 1) - user.login().then(function() { - user.get('permissions').then(function(permissions) { - return permissions.reload(); - }); - }); - ``` - - @method reload - @public - */ - reload(options) { - return this.relationship.reload(options); - }, - - /** - Saves all of the records in the `ManyArray`. - - Example - - ```javascript - store.findRecord('inbox', 1).then(function(inbox) { - inbox.get('messages').then(function(messages) { - messages.forEach(function(message) { - message.set('isRead', true); - }); - messages.save() - }); - }); - ``` - - @method save - @return {DS.PromiseArray} promise - */ - save() { - let manyArray = this; - let promiseLabel = 'DS: ManyArray#save ' + get(this, 'type'); - let promise = all(this.invoke('save'), promiseLabel).then( - () => manyArray, - null, - 'DS: ManyArray#save return ManyArray' - ); - - return PromiseArray.create({ promise }); - }, - - /** - Create a child record within the owner - - @method createRecord - @private - @param {Object} hash - @return {DS.Model} record - */ - createRecord(hash) { - const store = get(this, 'store'); - const type = get(this, 'type'); - - assert( - `You cannot add '${type.modelName}' records to this polymorphic relationship.`, - !get(this, 'isPolymorphic') - ); - let record = store.createRecord(type.modelName, hash); - this.pushObject(record); - - return record; - }, -}); diff --git a/addon/-legacy-private/system/model/internal-model.js b/addon/-legacy-private/system/model/internal-model.js deleted file mode 100644 index 73d53c4c2cd..00000000000 --- a/addon/-legacy-private/system/model/internal-model.js +++ /dev/null @@ -1,1404 +0,0 @@ -import { A } from '@ember/array'; -import { set, get } from '@ember/object'; -import { assign } from '@ember/polyfills'; -import EmberError from '@ember/error'; -import { isEqual } from '@ember/utils'; -import { setOwner } from '@ember/application'; -import { run } from '@ember/runloop'; -import RSVP, { Promise } from 'rsvp'; -import Ember from 'ember'; -import { DEBUG } from '@glimmer/env'; -import { assert, inspect } from '@ember/debug'; -import RootState from './states'; -import Relationships from '../relationships/state/create'; -import Snapshot from '../snapshot'; -import OrderedSet from '../ordered-set'; -import isArrayLike from '../is-array-like'; - -import { getOwner } from '../../utils'; - -import { RecordReference, BelongsToReference, HasManyReference } from '../references'; - -/* - The TransitionChainMap caches the `state.enters`, `state.setups`, and final state reached - when transitioning from one state to another, so that future transitions can replay the - transition without needing to walk the state tree, collect these hook calls and determine - the state to transition into. - - A future optimization would be to build a single chained method out of the collected enters - and setups. It may also be faster to do a two level cache (from: { to }) instead of caching based - on a key that adds the two together. - */ -const TransitionChainMap = Object.create(null); - -const _extractPivotNameCache = Object.create(null); -const _splitOnDotCache = Object.create(null); - -function splitOnDot(name) { - return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); -} - -function extractPivotName(name) { - return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); -} - -function areAllModelsUnloaded(internalModels) { - for (let i = 0; i < internalModels.length; ++i) { - let record = internalModels[i]._record; - if (record && !(record.get('isDestroyed') || record.get('isDestroying'))) { - return false; - } - } - return true; -} - -// Handle dematerialization for relationship `rel`. In all cases, notify the -// relationship of the dematerialization: this is done so the relationship can -// notify its inverse which needs to update state -// -// If the inverse is sync, unloading this record is treated as a client-side -// delete, so we remove the inverse records from this relationship to -// disconnect the graph. Because it's not async, we don't need to keep around -// the internalModel as an id-wrapper for references and because the graph is -// disconnected we can actually destroy the internalModel when checking for -// orphaned models. -function destroyRelationship(rel) { - rel.internalModelDidDematerialize(); - - if (rel._inverseIsSync()) { - // disconnect the graph so that the sync inverse relationship does not - // prevent us from cleaning up during `_cleanupOrphanedInternalModels` - rel.removeAllInternalModelsFromOwn(); - rel.removeAllCanonicalInternalModelsFromOwn(); - } -} -// this (and all heimdall instrumentation) will be stripped by a babel transform -// https://github.com/heimdalljs/babel5-plugin-strip-heimdall -const { - _triggerDeferredTriggers, - changedAttributes, - createSnapshot, - flushChangedAttributes, - hasChangedAttributes, - materializeRecord, - new_InternalModel, - send, - setupData, - transitionTo, - updateChangedAttributes, -} = heimdall.registerMonitor( - 'InternalModel', - '_triggerDeferredTriggers', - 'changedAttributes', - 'createSnapshot', - 'flushChangedAttributes', - 'hasChangedAttributes', - 'materializeRecord', - 'new_InternalModel', - 'send', - 'setupData', - 'transitionTo', - 'updateChangedAttributes' -); - -let InternalModelReferenceId = 1; -let nextBfsId = 1; - -/* - `InternalModel` is the Model class that we use internally inside Ember Data to represent models. - Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. - - We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as - a performance optimization. - - `InternalModel` should never be exposed to application code. At the boundaries of the system, in places - like `find`, `push`, etc. we convert between Models and InternalModels. - - We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` - if they are needed. - - @private - @class InternalModel -*/ -export default class InternalModel { - constructor(modelName, id, store, data) { - heimdall.increment(new_InternalModel); - this.id = id; - - // this ensure ordered set can quickly identify this as unique - this[Ember.GUID_KEY] = InternalModelReferenceId++ + 'internal-model'; - - this.store = store; - this.modelName = modelName; - this._promiseProxy = null; - this._record = null; - this._isDestroyed = false; - this.isError = false; - this._pendingRecordArrayManagerFlush = false; // used by the recordArrayManager - - // During dematerialization we don't want to rematerialize the record. The - // reason this might happen is that dematerialization removes records from - // record arrays, and Ember arrays will always `objectAt(0)` and - // `objectAt(len - 1)` to test whether or not `firstObject` or `lastObject` - // have changed. - this._isDematerializing = false; - this._scheduledDestroy = null; - - this.resetRecord(); - - if (data) { - this.__data = data; - } - - // caches for lazy getters - this._modelClass = null; - this.__deferredTriggers = null; - this.__recordArrays = null; - this._references = null; - this._recordReference = null; - this.__relationships = null; - this.__implicitRelationships = null; - - // Used during the mark phase of unloading to avoid checking the same internal - // model twice in the same scan - this._bfsId = 0; - } - - get modelClass() { - return this._modelClass || (this._modelClass = this.store.modelFor(this.modelName)); - } - - get type() { - return this.modelClass; - } - - get recordReference() { - if (this._recordReference === null) { - this._recordReference = new RecordReference(this.store, this); - } - return this._recordReference; - } - - get _recordArrays() { - if (this.__recordArrays === null) { - this.__recordArrays = new OrderedSet(); - } - return this.__recordArrays; - } - - get references() { - if (this._references === null) { - this._references = Object.create(null); - } - return this._references; - } - - get _deferredTriggers() { - if (this.__deferredTriggers === null) { - this.__deferredTriggers = []; - } - return this.__deferredTriggers; - } - - get _attributes() { - if (this.__attributes === null) { - this.__attributes = Object.create(null); - } - return this.__attributes; - } - - set _attributes(v) { - this.__attributes = v; - } - - get _relationships() { - if (this.__relationships === null) { - this.__relationships = new Relationships(this); - } - - return this.__relationships; - } - - get _inFlightAttributes() { - if (this.__inFlightAttributes === null) { - this.__inFlightAttributes = Object.create(null); - } - return this.__inFlightAttributes; - } - - set _inFlightAttributes(v) { - this.__inFlightAttributes = v; - } - - get _data() { - if (this.__data === null) { - this.__data = Object.create(null); - } - return this.__data; - } - - set _data(v) { - this.__data = v; - } - - /* - implicit relationships are relationship which have not been declared but the inverse side exists on - another record somewhere - For example if there was - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - name: DS.attr() - }) - ``` - - but there is also - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - name: DS.attr(), - comments: DS.hasMany('comment') - }) - ``` - - would have a implicit post relationship in order to be do things like remove ourselves from the post - when we are deleted - */ - get _implicitRelationships() { - if (this.__implicitRelationships === null) { - this.__implicitRelationships = Object.create(null); - } - return this.__implicitRelationships; - } - - isHiddenFromRecordArrays() { - // During dematerialization we don't want to rematerialize the record. - // recordWasDeleted can cause other records to rematerialize because it - // removes the internal model from the array and Ember arrays will always - // `objectAt(0)` and `objectAt(len -1)` to check whether `firstObject` or - // `lastObject` have changed. When this happens we don't want those - // models to rematerialize their records. - - return ( - this._isDematerializing || - this.hasScheduledDestroy() || - this.isDestroyed || - this.currentState.stateName === 'root.deleted.saved' || - this.isEmpty() - ); - } - - isEmpty() { - return this.currentState.isEmpty; - } - - isLoading() { - return this.currentState.isLoading; - } - - isLoaded() { - return this.currentState.isLoaded; - } - - hasDirtyAttributes() { - return this.currentState.hasDirtyAttributes; - } - - isSaving() { - return this.currentState.isSaving; - } - - isDeleted() { - return this.currentState.isDeleted; - } - - isNew() { - return this.currentState.isNew; - } - - isValid() { - return this.currentState.isValid; - } - - dirtyType() { - return this.currentState.dirtyType; - } - - getRecord(properties) { - if (!this._record && !this._isDematerializing) { - heimdall.increment(materializeRecord); - let token = heimdall.start('InternalModel.getRecord'); - - // lookupFactory should really return an object that creates - // instances with the injections applied - let createOptions = { - store: this.store, - _internalModel: this, - currentState: this.currentState, - isError: this.isError, - adapterError: this.error, - }; - - if (properties !== undefined) { - assert( - `You passed '${properties}' as properties for record creation instead of an object.`, - typeof properties === 'object' && properties !== null - ); - let classFields = this.getFields(); - let relationships = this._relationships; - let propertyNames = Object.keys(properties); - - for (let i = 0; i < propertyNames.length; i++) { - let name = propertyNames[i]; - let fieldType = classFields.get(name); - let propertyValue = properties[name]; - - if (name === 'id') { - this.setId(propertyValue); - continue; - } - - switch (fieldType) { - case 'attribute': - this.setDirtyAttribute(name, propertyValue); - break; - case 'belongsTo': - this.setDirtyBelongsTo(name, propertyValue); - relationships.get(name).setHasAnyRelationshipData(true); - relationships.get(name).setRelationshipIsEmpty(false); - break; - case 'hasMany': - this.setDirtyHasMany(name, propertyValue); - relationships.get(name).setHasAnyRelationshipData(true); - relationships.get(name).setRelationshipIsEmpty(false); - break; - default: - createOptions[name] = propertyValue; - } - } - } - - if (setOwner) { - // ensure that `getOwner(this)` works inside a model instance - setOwner(createOptions, getOwner(this.store)); - } else { - createOptions.container = this.store.container; - } - - this._record = this.store._modelFactoryFor(this.modelName).create(createOptions); - - this._triggerDeferredTriggers(); - heimdall.stop(token); - } - - return this._record; - } - - getFields() { - return get(this.modelClass, 'fields'); - } - - resetRecord() { - this._record = null; - this.isReloading = false; - this.error = null; - this.currentState = RootState.empty; - this.__attributes = null; - this.__inFlightAttributes = null; - this._data = null; - } - - dematerializeRecord() { - this._isDematerializing = true; - - if (this._record) { - this._record.destroy(); - } - - // move to an empty never-loaded state - this.destroyRelationships(); - this.resetRecord(); - this.updateRecordArrays(); - } - - deleteRecord() { - this.send('deleteRecord'); - } - - save(options) { - let promiseLabel = 'DS: Model#save ' + this; - let resolver = RSVP.defer(promiseLabel); - - this.store.scheduleSave(this, resolver, options); - return resolver.promise; - } - - startedReloading() { - this.isReloading = true; - if (this.hasRecord) { - set(this._record, 'isReloading', true); - } - } - - finishedReloading() { - this.isReloading = false; - if (this.hasRecord) { - set(this._record, 'isReloading', false); - } - } - - reload(options) { - this.startedReloading(); - let internalModel = this; - let promiseLabel = 'DS: Model#reload of ' + this; - - return new Promise(function(resolve) { - internalModel.send('reloadRecord', { resolve, options }); - }, promiseLabel) - .then( - function() { - internalModel.didCleanError(); - return internalModel; - }, - function(error) { - internalModel.didError(error); - throw error; - }, - 'DS: Model#reload complete, update flags' - ) - .finally(function() { - internalModel.finishedReloading(); - internalModel.updateRecordArrays(); - }); - } - - /* - Computes the set of internal models reachable from `this` across exactly one - relationship. - - @return {Array} An array containing the internal models that `this` belongs - to or has many. - */ - _directlyRelatedInternalModels() { - let array = []; - - this._relationships.forEach((name, rel) => { - array = array.concat(rel.members.list, rel.canonicalMembers.list); - }); - return array; - } - - /* - Computes the set of internal models reachable from this internal model. - - Reachability is determined over the relationship graph (ie a graph where - nodes are internal models and edges are belongs to or has many - relationships). - - @return {Array} An array including `this` and all internal models reachable - from `this`. - */ - _allRelatedInternalModels() { - let array = []; - let queue = []; - let bfsId = nextBfsId++; - queue.push(this); - this._bfsId = bfsId; - while (queue.length > 0) { - let node = queue.shift(); - array.push(node); - let related = node._directlyRelatedInternalModels(); - for (let i = 0; i < related.length; ++i) { - let internalModel = related[i]; - assert('Internal Error: seen a future bfs iteration', internalModel._bfsId <= bfsId); - if (internalModel._bfsId < bfsId) { - queue.push(internalModel); - internalModel._bfsId = bfsId; - } - } - } - return array; - } - - /* - Unload the record for this internal model. This will cause the record to be - destroyed and freed up for garbage collection. It will also do a check - for cleaning up internal models. - - This check is performed by first computing the set of related internal - models. If all records in this set are unloaded, then the entire set is - destroyed. Otherwise, nothing in the set is destroyed. - - This means that this internal model will be freed up for garbage collection - once all models that refer to it via some relationship are also unloaded. - */ - unloadRecord() { - if (this.isDestroyed) { - return; - } - this.send('unloadRecord'); - this.dematerializeRecord(); - - if (this._scheduledDestroy === null) { - this._scheduledDestroy = run.backburner.schedule( - 'destroy', - this, - '_checkForOrphanedInternalModels' - ); - } - } - - hasScheduledDestroy() { - return !!this._scheduledDestroy; - } - - cancelDestroy() { - assert( - `You cannot cancel the destruction of an InternalModel once it has already been destroyed`, - !this.isDestroyed - ); - - this._isDematerializing = false; - run.cancel(this._scheduledDestroy); - this._scheduledDestroy = null; - } - - // typically, we prefer to async destroy this lets us batch cleanup work. - // Unfortunately, some scenarios where that is not possible. Such as: - // - // ```js - // const record = store.find(‘record’, 1); - // record.unloadRecord(); - // store.createRecord(‘record’, 1); - // ``` - // - // In those scenarios, we make that model's cleanup work, sync. - // - destroySync() { - if (this._isDematerializing) { - this.cancelDestroy(); - } - this._checkForOrphanedInternalModels(); - if (this.isDestroyed || this.isDestroying) { - return; - } - - // just in-case we are not one of the orphaned, we should still - // still destroy ourselves - this.destroy(); - } - - _checkForOrphanedInternalModels() { - this._isDematerializing = false; - this._scheduledDestroy = null; - if (this.isDestroyed) { - return; - } - - this._cleanupOrphanedInternalModels(); - } - - _cleanupOrphanedInternalModels() { - let relatedInternalModels = this._allRelatedInternalModels(); - if (areAllModelsUnloaded(relatedInternalModels)) { - for (let i = 0; i < relatedInternalModels.length; ++i) { - let internalModel = relatedInternalModels[i]; - if (!internalModel.isDestroyed) { - internalModel.destroy(); - } - } - } - } - - eachRelationship(callback, binding) { - return this.modelClass.eachRelationship(callback, binding); - } - - destroy() { - assert( - 'Cannot destroy an internalModel while its record is materialized', - !this._record || this._record.get('isDestroyed') || this._record.get('isDestroying') - ); - this.isDestroying = true; - this.store._internalModelDestroyed(this); - - this._relationships.forEach((name, rel) => rel.destroy()); - - this._isDestroyed = true; - } - - eachAttribute(callback, binding) { - return this.modelClass.eachAttribute(callback, binding); - } - - inverseFor(key) { - return this.modelClass.inverseFor(key); - } - - setupData(data) { - heimdall.increment(setupData); - this.store._internalModelDidReceiveRelationshipData( - this.modelName, - this.id, - data.relationships - ); - - let changedKeys; - - if (this.hasRecord) { - changedKeys = this._changedKeys(data.attributes); - } - - assign(this._data, data.attributes); - this.pushedData(); - - if (this.hasRecord) { - this._record._notifyProperties(changedKeys); - } - } - - getAttributeValue(key) { - if (key in this._attributes) { - return this._attributes[key]; - } else if (key in this._inFlightAttributes) { - return this._inFlightAttributes[key]; - } else { - return this._data[key]; - } - } - - setDirtyHasMany(key, records) { - assert(`You must pass an array of records to set a hasMany relationship`, isArrayLike(records)); - assert( - `All elements of a hasMany relationship must be instances of DS.Model, you passed ${inspect( - records - )}`, - (function() { - return A(records).every(record => record.hasOwnProperty('_internalModel') === true); - })() - ); - - let relationship = this._relationships.get(key); - relationship.clear(); - relationship.addInternalModels(records.map(record => get(record, '_internalModel'))); - } - - setDirtyBelongsTo(key, value) { - if (value === undefined) { - value = null; - } - if (value && value.then) { - this._relationships.get(key).setRecordPromise(value); - } else if (value) { - this._relationships.get(key).setInternalModel(value._internalModel); - } else { - this._relationships.get(key).setInternalModel(value); - } - } - - setDirtyAttribute(key, value) { - if (this.isDeleted()) { - throw new EmberError(`Attempted to set '${key}' to '${value}' on the deleted record ${this}`); - } - - let oldValue = this.getAttributeValue(key); - let originalValue; - - if (value !== oldValue) { - // Add the new value to the changed attributes hash; it will get deleted by - // the 'didSetProperty' handler if it is no different from the original value - this._attributes[key] = value; - - if (key in this._inFlightAttributes) { - originalValue = this._inFlightAttributes[key]; - } else { - originalValue = this._data[key]; - } - - this.send('didSetProperty', { - name: key, - oldValue: oldValue, - originalValue: originalValue, - value: value, - }); - } - - return value; - } - - get isDestroyed() { - return this._isDestroyed; - } - - get hasRecord() { - return !!this._record; - } - - /* - @method createSnapshot - @private - */ - createSnapshot(options) { - heimdall.increment(createSnapshot); - return new Snapshot(this, options); - } - - /* - @method loadingData - @private - @param {Promise} promise - */ - loadingData(promise) { - this.send('loadingData', promise); - } - - /* - @method loadedData - @private - */ - loadedData() { - this.send('loadedData'); - } - - /* - @method notFound - @private - */ - notFound() { - this.send('notFound'); - } - - /* - @method pushedData - @private - */ - pushedData() { - this.send('pushedData'); - } - - flushChangedAttributes() { - heimdall.increment(flushChangedAttributes); - this._inFlightAttributes = this._attributes; - this._attributes = null; - } - - hasChangedAttributes() { - heimdall.increment(hasChangedAttributes); - return this.__attributes !== null && Object.keys(this.__attributes).length > 0; - } - - /* - Checks if the attributes which are considered as changed are still - different to the state which is acknowledged by the server. - - This method is needed when data for the internal model is pushed and the - pushed data might acknowledge dirty attributes as confirmed. - - @method updateChangedAttributes - @private - */ - updateChangedAttributes() { - heimdall.increment(updateChangedAttributes); - let changedAttributes = this.changedAttributes(); - let changedAttributeNames = Object.keys(changedAttributes); - let attrs = this._attributes; - - for (let i = 0, length = changedAttributeNames.length; i < length; i++) { - let attribute = changedAttributeNames[i]; - let data = changedAttributes[attribute]; - let oldData = data[0]; - let newData = data[1]; - - if (oldData === newData) { - delete attrs[attribute]; - } - } - } - - /* - Returns an object, whose keys are changed properties, and value is an - [oldProp, newProp] array. - - @method changedAttributes - @private - */ - changedAttributes() { - heimdall.increment(changedAttributes); - let oldData = this._data; - let currentData = this._attributes; - let inFlightData = this._inFlightAttributes; - let newData = assign({}, inFlightData, currentData); - let diffData = Object.create(null); - let newDataKeys = Object.keys(newData); - - for (let i = 0, length = newDataKeys.length; i < length; i++) { - let key = newDataKeys[i]; - diffData[key] = [oldData[key], newData[key]]; - } - - return diffData; - } - - /* - @method adapterWillCommit - @private - */ - adapterWillCommit() { - this.send('willCommit'); - } - - /* - @method adapterDidDirty - @private - */ - adapterDidDirty() { - this.send('becomeDirty'); - this.updateRecordArrays(); - } - - /* - @method send - @private - @param {String} name - @param {Object} context - */ - send(name, context) { - heimdall.increment(send); - let currentState = this.currentState; - - if (!currentState[name]) { - this._unhandledEvent(currentState, name, context); - } - - return currentState[name](this, context); - } - - notifyHasManyAdded(key, record, idx) { - if (this.hasRecord) { - this._record.notifyHasManyAdded(key, record, idx); - } - } - - notifyBelongsToChange(key, record) { - if (this.hasRecord) { - this._record.notifyBelongsToChange(key, record); - } - } - - notifyPropertyChange(key) { - if (this.hasRecord) { - this._record.notifyPropertyChange(key); - } - } - - rollbackAttributes() { - let dirtyKeys; - if (this.hasChangedAttributes()) { - dirtyKeys = Object.keys(this._attributes); - this._attributes = null; - } - - if (get(this, 'isError')) { - this._inFlightAttributes = null; - this.didCleanError(); - } - - if (this.isNew()) { - this.removeFromInverseRelationships(); - } - - if (this.isValid()) { - this._inFlightAttributes = null; - } - - this.send('rolledBack'); - - if (dirtyKeys && dirtyKeys.length > 0) { - this._record._notifyProperties(dirtyKeys); - } - } - - /* - @method transitionTo - @private - @param {String} name - */ - transitionTo(name) { - heimdall.increment(transitionTo); - // POSSIBLE TODO: Remove this code and replace with - // always having direct reference to state objects - - let pivotName = extractPivotName(name); - let state = this.currentState; - let transitionMapId = `${state.stateName}->${name}`; - - do { - if (state.exit) { - state.exit(this); - } - state = state.parentState; - } while (!state[pivotName]); - - let setups; - let enters; - let i; - let l; - let map = TransitionChainMap[transitionMapId]; - - if (map) { - setups = map.setups; - enters = map.enters; - state = map.state; - } else { - setups = []; - enters = []; - - let path = splitOnDot(name); - - for (i = 0, l = path.length; i < l; i++) { - state = state[path[i]]; - - if (state.enter) { - enters.push(state); - } - if (state.setup) { - setups.push(state); - } - } - - TransitionChainMap[transitionMapId] = { setups, enters, state }; - } - - for (i = 0, l = enters.length; i < l; i++) { - enters[i].enter(this); - } - - this.currentState = state; - if (this.hasRecord) { - set(this._record, 'currentState', state); - } - - for (i = 0, l = setups.length; i < l; i++) { - setups[i].setup(this); - } - - this.updateRecordArrays(); - } - - _unhandledEvent(state, name, context) { - let errorMessage = 'Attempted to handle event `' + name + '` '; - errorMessage += 'on ' + String(this) + ' while in state '; - errorMessage += state.stateName + '. '; - - if (context !== undefined) { - errorMessage += 'Called with ' + inspect(context) + '.'; - } - - throw new EmberError(errorMessage); - } - - triggerLater(...args) { - if (this._deferredTriggers.push(args) !== 1) { - return; - } - - this.store._updateInternalModel(this); - } - - _triggerDeferredTriggers() { - heimdall.increment(_triggerDeferredTriggers); - //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, - //but for now, we queue up all the events triggered before the record was materialized, and flush - //them once we have the record - if (!this.hasRecord) { - return; - } - let triggers = this._deferredTriggers; - let record = this._record; - let trigger = record.trigger; - for (let i = 0, l = triggers.length; i < l; i++) { - trigger.apply(record, triggers[i]); - } - - triggers.length = 0; - } - - /* - This method should only be called by records in the `isNew()` state OR once the record - has been deleted and that deletion has been persisted. - - It will remove this record from any associated relationships. - - @method removeFromInverseRelationships - @private - */ - removeFromInverseRelationships() { - this._relationships.forEach((name, rel) => { - rel.removeCompletelyFromInverse(); - rel.clear(); - }); - - let implicitRelationships = this._implicitRelationships; - this.__implicitRelationships = null; - - Object.keys(implicitRelationships).forEach(key => { - let rel = implicitRelationships[key]; - - rel.removeCompletelyFromInverse(); - rel.clear(); - }); - } - - /* - Notify all inverses that this internalModel has been dematerialized - and destroys any ManyArrays. - */ - destroyRelationships() { - let relationships = this._relationships; - relationships.forEach((name, rel) => destroyRelationship(rel)); - - let implicitRelationships = this._implicitRelationships; - this.__implicitRelationships = null; - Object.keys(implicitRelationships).forEach(key => { - let rel = implicitRelationships[key]; - destroyRelationship(rel); - }); - } - - /* - When a find request is triggered on the store, the user can optionally pass in - attributes and relationships to be preloaded. These are meant to behave as if they - came back from the server, except the user obtained them out of band and is informing - the store of their existence. The most common use case is for supporting client side - nested URLs, such as `/posts/1/comments/2` so the user can do - `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post. - - Preloaded data can be attributes and relationships passed in either as IDs or as actual - models. - - @method preloadData - @private - @param {Object} preload - */ - preloadData(preload) { - //TODO(Igor) consider the polymorphic case - Object.keys(preload).forEach(key => { - let preloadValue = get(preload, key); - let relationshipMeta = this.modelClass.metaForProperty(key); - if (relationshipMeta.isRelationship) { - this._preloadRelationship(key, preloadValue); - } else { - this._data[key] = preloadValue; - } - }); - } - - _preloadRelationship(key, preloadValue) { - let relationshipMeta = this.modelClass.metaForProperty(key); - let modelClass = relationshipMeta.type; - if (relationshipMeta.kind === 'hasMany') { - this._preloadHasMany(key, preloadValue, modelClass); - } else { - this._preloadBelongsTo(key, preloadValue, modelClass); - } - } - - _preloadHasMany(key, preloadValue, modelClass) { - assert( - 'You need to pass in an array to set a hasMany property on a record', - Array.isArray(preloadValue) - ); - let recordsToSet = new Array(preloadValue.length); - - for (let i = 0; i < preloadValue.length; i++) { - let recordToPush = preloadValue[i]; - recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass); - } - - //We use the pathway of setting the hasMany as if it came from the adapter - //because the user told us that they know this relationships exists already - this._relationships.get(key).updateInternalModelsFromAdapter(recordsToSet); - } - - _preloadBelongsTo(key, preloadValue, modelClass) { - let internalModelToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass); - - //We use the pathway of setting the hasMany as if it came from the adapter - //because the user told us that they know this relationships exists already - this._relationships.get(key).setInternalModel(internalModelToSet); - } - - _convertStringOrNumberIntoInternalModel(value, modelClass) { - if (typeof value === 'string' || typeof value === 'number') { - return this.store._internalModelForId(modelClass, value); - } - if (value._internalModel) { - return value._internalModel; - } - return value; - } - - /* - Used to notify the store to update FilteredRecordArray membership. - - @method updateRecordArrays - @private - */ - updateRecordArrays() { - this.store.recordArrayManager.recordDidChange(this); - } - - setId(id) { - assert( - "A record's id cannot be changed once it is in the loaded state", - this.id === null || this.id === id || this.isNew() - ); - let didChange = id !== this.id; - this.id = id; - - if (didChange && this.hasRecord) { - this._record.notifyPropertyChange('id'); - } - } - - didError(error) { - this.error = error; - this.isError = true; - - if (this.hasRecord) { - this._record.setProperties({ - isError: true, - adapterError: error, - }); - } - } - - didCleanError() { - this.error = null; - this.isError = false; - - if (this.hasRecord) { - this._record.setProperties({ - isError: false, - adapterError: null, - }); - } - } - - /* - If the adapter did not return a hash in response to a commit, - merge the changed attributes and relationships into the existing - saved data. - - @method adapterDidCommit - */ - adapterDidCommit(data) { - if (data) { - this.store._internalModelDidReceiveRelationshipData( - this.modelName, - this.id, - data.relationships - ); - - data = data.attributes; - } - - this.didCleanError(); - let changedKeys = this._changedKeys(data); - - assign(this._data, this._inFlightAttributes); - if (data) { - assign(this._data, data); - } - - this._inFlightAttributes = null; - - this.send('didCommit'); - this.updateRecordArrays(); - - if (!data) { - return; - } - - this._record._notifyProperties(changedKeys); - } - - addErrorMessageToAttribute(attribute, message) { - get(this.getRecord(), 'errors')._add(attribute, message); - } - - removeErrorMessageFromAttribute(attribute) { - get(this.getRecord(), 'errors')._remove(attribute); - } - - clearErrorMessages() { - get(this.getRecord(), 'errors')._clear(); - } - - hasErrors() { - let errors = get(this.getRecord(), 'errors'); - - return errors.get('length') > 0; - } - - // FOR USE DURING COMMIT PROCESS - - /* - @method adapterDidInvalidate - @private - */ - adapterDidInvalidate(errors) { - let attribute; - - for (attribute in errors) { - if (errors.hasOwnProperty(attribute)) { - this.addErrorMessageToAttribute(attribute, errors[attribute]); - } - } - - this.send('becameInvalid'); - - this._saveWasRejected(); - } - - /* - @method adapterDidError - @private - */ - adapterDidError(error) { - this.send('becameError'); - this.didError(error); - this._saveWasRejected(); - } - - _saveWasRejected() { - let keys = Object.keys(this._inFlightAttributes); - if (keys.length > 0) { - let attrs = this._attributes; - for (let i = 0; i < keys.length; i++) { - if (attrs[keys[i]] === undefined) { - attrs[keys[i]] = this._inFlightAttributes[keys[i]]; - } - } - } - this._inFlightAttributes = null; - } - - /* - Ember Data has 3 buckets for storing the value of an attribute on an internalModel. - - `_data` holds all of the attributes that have been acknowledged by - a backend via the adapter. When rollbackAttributes is called on a model all - attributes will revert to the record's state in `_data`. - - `_attributes` holds any change the user has made to an attribute - that has not been acknowledged by the adapter. Any values in - `_attributes` are have priority over values in `_data`. - - `_inFlightAttributes`. When a record is being synced with the - backend the values in `_attributes` are copied to - `_inFlightAttributes`. This way if the backend acknowledges the - save but does not return the new state Ember Data can copy the - values from `_inFlightAttributes` to `_data`. Without having to - worry about changes made to `_attributes` while the save was - happenign. - - - Changed keys builds a list of all of the values that may have been - changed by the backend after a successful save. - - It does this by iterating over each key, value pair in the payload - returned from the server after a save. If the `key` is found in - `_attributes` then the user has a local changed to the attribute - that has not been synced with the server and the key is not - included in the list of changed keys. - - - - If the value, for a key differs from the value in what Ember Data - believes to be the truth about the backend state (A merger of the - `_data` and `_inFlightAttributes` objects where - `_inFlightAttributes` has priority) then that means the backend - has updated the value and the key is added to the list of changed - keys. - - @method _changedKeys - @private - */ - _changedKeys(updates) { - let changedKeys = []; - - if (updates) { - let original, i, value, key; - let keys = Object.keys(updates); - let length = keys.length; - let hasAttrs = this.hasChangedAttributes(); - let attrs; - if (hasAttrs) { - attrs = this._attributes; - } - - original = Object.create(null); - assign(original, this._data, this._inFlightAttributes); - - for (i = 0; i < length; i++) { - key = keys[i]; - value = updates[key]; - - // A value in _attributes means the user has a local change to - // this attributes. We never override this value when merging - // updates from the backend so we should not sent a change - // notification if the server value differs from the original. - if (hasAttrs === true && attrs[key] !== undefined) { - continue; - } - - if (!isEqual(original[key], value)) { - changedKeys.push(key); - } - } - } - - return changedKeys; - } - - toString() { - return `<${this.modelName}:${this.id}>`; - } - - referenceFor(kind, name) { - let reference = this.references[name]; - - if (!reference) { - let relationship = this._relationships.get(name); - - if (DEBUG) { - let modelName = this.modelName; - assert( - `There is no ${kind} relationship named '${name}' on a model of modelClass '${modelName}'`, - relationship - ); - - let actualRelationshipKind = relationship.relationshipMeta.kind; - assert( - `You tried to get the '${name}' relationship on a '${modelName}' via record.${kind}('${name}'), but the relationship is of kind '${actualRelationshipKind}'. Use record.${actualRelationshipKind}('${name}') instead.`, - actualRelationshipKind === kind - ); - } - - if (kind === 'belongsTo') { - reference = new BelongsToReference(this.store, this, relationship); - } else if (kind === 'hasMany') { - reference = new HasManyReference(this.store, this, relationship); - } - - this.references[name] = reference; - } - - return reference; - } -} diff --git a/addon/-legacy-private/system/model/model.js b/addon/-legacy-private/system/model/model.js deleted file mode 100644 index b6218147c56..00000000000 --- a/addon/-legacy-private/system/model/model.js +++ /dev/null @@ -1,1994 +0,0 @@ -import ComputedProperty from '@ember/object/computed'; -import { isNone } from '@ember/utils'; -import EmberError from '@ember/error'; -import Evented from '@ember/object/evented'; -import EmberObject, { computed, get } from '@ember/object'; -import Map from '../map'; -import { DEBUG } from '@glimmer/env'; -import { assert, warn } from '@ember/debug'; -import { PromiseObject } from '../promise-proxies'; -import Errors from '../model/errors'; -import RootState from '../model/states'; -import { - relationshipsByNameDescriptor, - relatedTypesDescriptor, - relationshipsDescriptor, -} from '../relationships/ext'; - -import Ember from 'ember'; -const { changeProperties } = Ember; - -/** - @module ember-data -*/ - -function findPossibleInverses(type, inverseType, name, relationshipsSoFar) { - let possibleRelationships = relationshipsSoFar || []; - - let relationshipMap = get(inverseType, 'relationships'); - if (!relationshipMap) { - return possibleRelationships; - } - - let relationships = relationshipMap.get(type.modelName).filter(relationship => { - let optionsForRelationship = inverseType.metaForProperty(relationship.name).options; - - if (!optionsForRelationship.inverse && optionsForRelationship.inverse !== null) { - return true; - } - - return name === optionsForRelationship.inverse; - }); - - if (relationships) { - possibleRelationships.push.apply(possibleRelationships, relationships); - } - - //Recurse to support polymorphism - if (type.superclass) { - findPossibleInverses(type.superclass, inverseType, name, possibleRelationships); - } - - return possibleRelationships; -} - -function intersection(array1, array2) { - let result = []; - array1.forEach(element => { - if (array2.indexOf(element) >= 0) { - result.push(element); - } - }); - - return result; -} - -const RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; - -const retrieveFromCurrentState = computed('currentState', function(key) { - return get(this._internalModel.currentState, key); -}).readOnly(); - -/** - - The model class that all Ember Data records descend from. - This is the public API of Ember Data models. If you are using Ember Data - in your application, this is the class you should use. - If you are working on Ember Data internals, you most likely want to be dealing - with `InternalModel` - - @class Model - @namespace DS - @extends Ember.Object - @uses Ember.Evented -*/ -const Model = EmberObject.extend(Evented, { - _internalModel: null, - store: null, - __defineNonEnumerable(property) { - this[property.name] = property.descriptor.value; - }, - - /** - If this property is `true` the record is in the `empty` - state. Empty is the first state all records enter after they have - been created. Most records created by the store will quickly - transition to the `loading` state if data needs to be fetched from - the server or the `created` state if the record is created on the - client. A record can also enter the empty state if the adapter is - unable to locate the record. - - @property isEmpty - @type {Boolean} - @readOnly - */ - isEmpty: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loading` state. A - record enters this state when the store asks the adapter for its - data. It remains in this state until the adapter provides the - requested data. - - @property isLoading - @type {Boolean} - @readOnly - */ - isLoading: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loaded` state. A - record enters this state when its data is populated. Most of a - record's lifecycle is spent inside substates of the `loaded` - state. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('isLoaded'); // true - - store.findRecord('model', 1).then(function(model) { - model.get('isLoaded'); // true - }); - ``` - - @property isLoaded - @type {Boolean} - @readOnly - */ - isLoaded: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `dirty` state. The - record has local changes that have not yet been saved by the - adapter. This includes records that have been created (but not yet - saved) or deleted. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('hasDirtyAttributes'); // true - - store.findRecord('model', 1).then(function(model) { - model.get('hasDirtyAttributes'); // false - model.set('foo', 'some value'); - model.get('hasDirtyAttributes'); // true - }); - ``` - - @since 1.13.0 - @property hasDirtyAttributes - @type {Boolean} - @readOnly - */ - hasDirtyAttributes: computed('currentState.isDirty', function() { - return this.get('currentState.isDirty'); - }), - /** - If this property is `true` the record is in the `saving` state. A - record enters the saving state when `save` is called, but the - adapter has not yet acknowledged that the changes have been - persisted to the backend. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('isSaving'); // false - let promise = record.save(); - record.get('isSaving'); // true - promise.then(function() { - record.get('isSaving'); // false - }); - ``` - - @property isSaving - @type {Boolean} - @readOnly - */ - isSaving: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `deleted` state - and has been marked for deletion. When `isDeleted` is true and - `hasDirtyAttributes` is true, the record is deleted locally but the deletion - was not yet persisted. When `isSaving` is true, the change is - in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the - change has persisted. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('isDeleted'); // false - record.deleteRecord(); - - // Locally deleted - record.get('isDeleted'); // true - record.get('hasDirtyAttributes'); // true - record.get('isSaving'); // false - - // Persisting the deletion - let promise = record.save(); - record.get('isDeleted'); // true - record.get('isSaving'); // true - - // Deletion Persisted - promise.then(function() { - record.get('isDeleted'); // true - record.get('isSaving'); // false - record.get('hasDirtyAttributes'); // false - }); - ``` - - @property isDeleted - @type {Boolean} - @readOnly - */ - isDeleted: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `new` state. A - record will be in the `new` state when it has been created on the - client and the adapter has not yet report that it was successfully - saved. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('isNew'); // true - - record.save().then(function(model) { - model.get('isNew'); // false - }); - ``` - - @property isNew - @type {Boolean} - @readOnly - */ - isNew: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `valid` state. - - A record will be in the `valid` state when the adapter did not report any - server-side validation failures. - - @property isValid - @type {Boolean} - @readOnly - */ - isValid: retrieveFromCurrentState, - /** - If the record is in the dirty state this property will report what - kind of change has caused it to move into the dirty - state. Possible values are: - - - `created` The record has been created by the client and not yet saved to the adapter. - - `updated` The record has been updated by the client and not yet saved to the adapter. - - `deleted` The record has been deleted by the client and not yet saved to the adapter. - - Example - - ```javascript - let record = store.createRecord('model'); - record.get('dirtyType'); // 'created' - ``` - - @property dirtyType - @type {String} - @readOnly - */ - dirtyType: retrieveFromCurrentState, - - /** - If `true` the adapter reported that it was unable to save local - changes to the backend for any reason other than a server-side - validation error. - - Example - - ```javascript - record.get('isError'); // false - record.set('foo', 'valid value'); - record.save().then(null, function() { - record.get('isError'); // true - }); - ``` - - @property isError - @type {Boolean} - @readOnly - */ - isError: false, - - /** - If `true` the store is attempting to reload the record from the adapter. - - Example - - ```javascript - record.get('isReloading'); // false - record.reload(); - record.get('isReloading'); // true - ``` - - @property isReloading - @type {Boolean} - @readOnly - */ - isReloading: false, - - /** - All ember models have an id property. This is an identifier - managed by an external source. These are always coerced to be - strings before being used internally. Note when declaring the - attributes for a model it is an error to declare an id - attribute. - - ```javascript - let record = store.createRecord('model'); - record.get('id'); // null - - store.findRecord('model', 1).then(function(model) { - model.get('id'); // '1' - }); - ``` - - @property id - @type {String} - */ - - /** - @property currentState - @private - @type {Object} - */ - currentState: RootState.empty, - - /** - When the record is in the `invalid` state this object will contain - any errors returned by the adapter. When present the errors hash - contains keys corresponding to the invalid property names - and values which are arrays of Javascript objects with two keys: - - - `message` A string containing the error message from the backend - - `attribute` The name of the property associated with this error message - - ```javascript - record.get('errors.length'); // 0 - record.set('foo', 'invalid value'); - record.save().catch(function() { - record.get('errors').get('foo'); - // [{message: 'foo should be a number.', attribute: 'foo'}] - }); - ``` - - The `errors` property us useful for displaying error messages to - the user. - - ```handlebars - - {{#each model.errors.username as |error|}} -
- {{error.message}} -
- {{/each}} - - {{#each model.errors.email as |error|}} -
- {{error.message}} -
- {{/each}} - ``` - - - You can also access the special `messages` property on the error - object to get an array of all the error strings. - - ```handlebars - {{#each model.errors.messages as |message|}} -
- {{message}} -
- {{/each}} - ``` - - @property errors - @type {DS.Errors} - */ - errors: computed(function() { - let errors = Errors.create(); - - errors._registerHandlers( - this._internalModel, - function() { - this.send('becameInvalid'); - }, - function() { - this.send('becameValid'); - } - ); - return errors; - }).readOnly(), - - /** - This property holds the `DS.AdapterError` object with which - last adapter operation was rejected. - - @property adapterError - @type {DS.AdapterError} - */ - adapterError: null, - - /** - Create a JSON representation of the record, using the serialization - strategy of the store's adapter. - - `serialize` takes an optional hash as a parameter, currently - supported options are: - - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - - @method serialize - @param {Object} options - @return {Object} an object whose values are primitive JSON values only - */ - serialize(options) { - return this._internalModel.createSnapshot().serialize(options); - }, - - /** - Use [DS.JSONSerializer](DS.JSONSerializer.html) to - get the JSON representation of a record. - - `toJSON` takes an optional hash as a parameter, currently - supported options are: - - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - - @method toJSON - @param {Object} options - @return {Object} A JSON representation of the object. - */ - toJSON(options) { - // container is for lazy transform lookups - let serializer = this.store.serializerFor('-default'); - let snapshot = this._internalModel.createSnapshot(); - - return serializer.serialize(snapshot, options); - }, - - /** - Fired when the record is ready to be interacted with, - that is either loaded from the server or created locally. - - @event ready - */ - ready: null, - - /** - Fired when the record is loaded from the server. - - @event didLoad - */ - didLoad: null, - - /** - Fired when the record is updated. - - @event didUpdate - */ - didUpdate: null, - - /** - Fired when a new record is commited to the server. - - @event didCreate - */ - didCreate: null, - - /** - Fired when the record is deleted. - - @event didDelete - */ - didDelete: null, - - /** - Fired when the record becomes invalid. - - @event becameInvalid - */ - becameInvalid: null, - - /** - Fired when the record enters the error state. - - @event becameError - */ - becameError: null, - - /** - Fired when the record is rolled back. - - @event rolledBack - */ - rolledBack: null, - - //TODO Do we want to deprecate these? - /** - @method send - @private - @param {String} name - @param {Object} context - */ - send(name, context) { - return this._internalModel.send(name, context); - }, - - /** - @method transitionTo - @private - @param {String} name - */ - transitionTo(name) { - return this._internalModel.transitionTo(name); - }, - - /** - Marks the record as deleted but does not save it. You must call - `save` afterwards if you want to persist it. You might use this - method if you want to allow the user to still `rollbackAttributes()` - after a delete was made. - - Example - - ```app/routes/model/delete.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - actions: { - softDelete() { - this.get('controller.model').deleteRecord(); - }, - confirm() { - this.get('controller.model').save(); - }, - undo() { - this.get('controller.model').rollbackAttributes(); - } - } - }); - ``` - - @method deleteRecord - */ - deleteRecord() { - this._internalModel.deleteRecord(); - }, - - /** - Same as `deleteRecord`, but saves the record immediately. - - Example - - ```app/routes/model/delete.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - actions: { - delete() { - this.get('controller.model').destroyRecord().then(function() { - controller.transitionToRoute('model.index'); - }); - } - } - }); - ``` - - If you pass an object on the `adapterOptions` property of the options - argument it will be passed to your adapter via the snapshot - - ```js - record.destroyRecord({ adapterOptions: { subscribe: false } }); - ``` - - ```app/adapters/post.js - import MyCustomAdapter from './custom-adapter'; - - export default MyCustomAdapter.extend({ - deleteRecord(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. - */ - destroyRecord(options) { - this.deleteRecord(); - return this.save(options); - }, - - /** - Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. - - @method unloadRecord - */ - unloadRecord() { - if (this.isDestroyed) { - return; - } - this._internalModel.unloadRecord(); - }, - - /** - @method _notifyProperties - @private - */ - _notifyProperties(keys) { - // changeProperties defers notifications until after the delegate - // and protects with a try...finally block - // previously used begin...endPropertyChanges but this is private API - changeProperties(() => { - let key; - for (let i = 0, length = keys.length; i < length; i++) { - key = keys[i]; - this.notifyPropertyChange(key); - } - }); - }, - - /** - Returns an object, whose keys are changed properties, and value is - an [oldProp, newProp] array. - - The array represents the diff of the canonical state with the local state - of the model. Note: if the model is created locally, the canonical state is - empty since the adapter hasn't acknowledged the attributes yet: - - Example - - ```app/models/mascot.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - name: DS.attr('string'), - isAdmin: DS.attr('boolean', { - defaultValue: false - }) - }); - ``` - - ```javascript - let mascot = store.createRecord('mascot'); - - mascot.changedAttributes(); // {} - - mascot.set('name', 'Tomster'); - mascot.changedAttributes(); // { name: [undefined, 'Tomster'] } - - mascot.set('isAdmin', true); - mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] } - - mascot.save().then(function() { - mascot.changedAttributes(); // {} - - mascot.set('isAdmin', false); - mascot.changedAttributes(); // { isAdmin: [true, false] } - }); - ``` - - @method changedAttributes - @return {Object} an object, whose keys are changed properties, - and value is an [oldProp, newProp] array. - */ - changedAttributes() { - return this._internalModel.changedAttributes(); - }, - - //TODO discuss with tomhuda about events/hooks - //Bring back as hooks? - /** - @method adapterWillCommit - @private - adapterWillCommit: function() { - this.send('willCommit'); - }, - - /** - @method adapterDidDirty - @private - adapterDidDirty: function() { - this.send('becomeDirty'); - this.updateRecordArraysLater(); - }, - */ - - /** - If the model `hasDirtyAttributes` this function will discard any unsaved - changes. If the model `isNew` it will be removed from the store. - - Example - - ```javascript - record.get('name'); // 'Untitled Document' - record.set('name', 'Doc 1'); - record.get('name'); // 'Doc 1' - record.rollbackAttributes(); - record.get('name'); // 'Untitled Document' - ``` - - @since 1.13.0 - @method rollbackAttributes - */ - rollbackAttributes() { - this._internalModel.rollbackAttributes(); - }, - - /* - @method _createSnapshot - @private - */ - _createSnapshot() { - return this._internalModel.createSnapshot(); - }, - - toStringExtension() { - // the _internalModel guard exists, because some dev-only deprecation code - // (addListener via validatePropertyInjections) invokes toString before the - // object is real. - return this._internalModel && this._internalModel.id; - }, - - /** - Save the record and persist any changes to the record to an - external source via the adapter. - - Example - - ```javascript - record.set('name', 'Tomster'); - record.save().then(function() { - // Success callback - }, function() { - // Error callback - }); - ``` - - If you pass an object using the `adapterOptions` property of the options - argument it will be passed to your adapter via the snapshot. - - ```js - record.save({ adapterOptions: { subscribe: false } }); - ``` - - ```app/adapters/post.js - import MyCustomAdapter from './custom-adapter'; - - export default MyCustomAdapter.extend({ - updateRecord(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(options) { - return PromiseObject.create({ - promise: this._internalModel.save(options).then(() => this), - }); - }, - - /** - Reload the record from the adapter. - - This will only work if the record has already finished loading. - - Example - - ```app/routes/model/view.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - actions: { - reload() { - this.controller.get('model').reload().then(function(model) { - // do something with the reloaded model - }); - } - } - }); - ``` - - @method reload - @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter request - - @return {Promise} a promise that will be resolved with the record when the - adapter returns successfully or rejected if the adapter returns - with an error. - */ - reload(options) { - let wrappedAdapterOptions; - - if (typeof options === 'object' && options !== null && options.adapterOptions) { - wrappedAdapterOptions = { - adapterOptions: options.adapterOptions, - }; - } - - return PromiseObject.create({ - promise: this._internalModel.reload(wrappedAdapterOptions).then(() => this), - }); - }, - - /** - Override the default event firing from Ember.Evented to - also call methods with the given name. - - @method trigger - @private - @param {String} name - */ - trigger(name) { - let fn = this[name]; - - if (typeof fn === 'function') { - let length = arguments.length; - let args = new Array(length - 1); - - for (let i = 1; i < length; i++) { - args[i - 1] = arguments[i]; - } - fn.apply(this, args); - } - - this._super(...arguments); - }, - - attr() { - assert( - 'The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?', - false - ); - }, - - /** - Get the reference for the specified belongsTo relationship. - - Example - - ```app/models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - ``` - - ```javascript - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - // check if the user relationship is loaded - let isLoaded = userRef.value() !== null; - - // get the record of the reference (null if not yet available) - let user = userRef.value(); - - // get the identifier of the reference - if (userRef.remoteType() === "id") { - let id = userRef.id(); - } else if (userRef.remoteType() === "link") { - let 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(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 }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - comments: { - data: [ - { type: 'comment', id: 1 }, - { type: 'comment', id: 2 } - ] - } - } - } - }); - let commentsRef = blog.hasMany('comments'); - - // check if the comments are loaded already - let isLoaded = commentsRef.value() !== null; - - // get the records of the reference (null if not yet available) - let comments = commentsRef.value(); - - // get the identifier of the reference - if (commentsRef.remoteType() === "ids") { - let ids = commentsRef.ids(); - } else if (commentsRef.remoteType() === "link") { - let 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(name) { - return this._internalModel.referenceFor('hasMany', name); - }, - - /** - Provides info about the model for debugging purposes - by grouping the properties into more semantic groups. - - Meant to be used by debugging tools such as the Chrome Ember Extension. - - - Groups all attributes in "Attributes" group. - - Groups all belongsTo relationships in "Belongs To" group. - - Groups all hasMany relationships in "Has Many" group. - - Groups all flags in "Flags" group. - - Flags relationship CPs as expensive properties. - - @method _debugInfo - @for DS.Model - @private - */ - _debugInfo() { - let attributes = ['id']; - let relationships = {}; - let expensiveProperties = []; - - this.eachAttribute((name, meta) => attributes.push(name)); - - let groups = [ - { - name: 'Attributes', - properties: attributes, - expand: true, - }, - ]; - - this.eachRelationship((name, relationship) => { - let properties = relationships[relationship.kind]; - - if (properties === undefined) { - properties = relationships[relationship.kind] = []; - groups.push({ - name: relationship.name, - properties, - expand: true, - }); - } - properties.push(name); - expensiveProperties.push(name); - }); - - groups.push({ - name: 'Flags', - properties: [ - 'isLoaded', - 'hasDirtyAttributes', - 'isSaving', - 'isDeleted', - 'isError', - 'isNew', - 'isValid', - ], - }); - - return { - propertyInfo: { - // include all other mixins / properties (not just the grouped ones) - includeOtherProperties: true, - groups: groups, - // don't pre-calculate unless cached - expensiveProperties: expensiveProperties, - }, - }; - }, - - notifyBelongsToChange(key) { - this.notifyPropertyChange(key); - }, - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - - The callback method you provide should have the following signature (all - parameters are optional): - - ```javascript - function(name, descriptor); - ``` - - - `name` the name of the current property in the iteration - - `descriptor` the meta object that describes this relationship - - The relationship descriptor argument is an object with the following properties. - - - **key** String the name of this relationship on the Model - - **kind** String "hasMany" or "belongsTo" - - **options** Object the original options hash passed when the relationship was declared - - **parentType** DS.Model the type of the Model that owns this relationship - - **type** String 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'; - - export default DS.JSONSerializer.extend({ - serialize: function(record, options) { - let json = {}; - - record.eachRelationship(function(name, descriptor) { - if (descriptor.kind === 'hasMany') { - let serializedHasManyName = name.toUpperCase() + '_IDS'; - json[serializedHasManyName] = record.get(name).mapBy('id'); - } - }); - - return json; - } - }); - ``` - - @method eachRelationship - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship(callback, binding) { - this.constructor.eachRelationship(callback, binding); - }, - - relationshipFor(name) { - return get(this.constructor, 'relationshipsByName').get(name); - }, - - inverseFor(key) { - return this.constructor.inverseFor(key, this.store); - }, - - notifyHasManyAdded(key) { - //We need to notifyPropertyChange in the adding case because we need to make sure - //we fetch the newly added record in case it is unloaded - //TODO(Igor): Consider whether we could do this only if the record state is unloaded - - //Goes away once hasMany is double promisified - this.notifyPropertyChange(key); - }, - - eachAttribute(callback, binding) { - this.constructor.eachAttribute(callback, binding); - }, -}); - -/** - @property data - @private - @type {Object} - */ -Object.defineProperty(Model.prototype, 'data', { - configurable: false, - get() { - return this._internalModel._data; - }, -}); - -Object.defineProperty(Model.prototype, 'id', { - configurable: false, - set(id) { - this._internalModel.setId(id); - }, - - get() { - // the _internalModel guard exists, because some dev-only deprecation code - // (addListener via validatePropertyInjections) invokes toString before the - // object is real. - return this._internalModel && this._internalModel.id; - }, -}); - -if (DEBUG) { - Model.reopen({ - init() { - this._super(...arguments); - - if (!this._internalModel) { - throw new EmberError( - 'You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.' - ); - } - }, - }); -} - -Model.reopenClass({ - isModel: true, - - /** - Override the class' `create()` method to raise an error. This - prevents end users from inadvertently calling `create()` instead - of `createRecord()`. The store is still able to create instances - by calling the `_create()` method. To create an instance of a - `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). - - @method create - @private - @static - */ - /** - Represents the model's class name as a string. This can be used to look up the model's class name through - `DS.Store`'s modelFor method. - - `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. - For example: - - ```javascript - store.modelFor('post').modelName; // 'post' - store.modelFor('blog-post').modelName; // 'blog-post' - ``` - - The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload - keys to underscore (instead of dasherized), you might use the following code: - - ```javascript - import { underscore } from '@ember/string'; - - export default const PostSerializer = DS.RESTSerializer.extend({ - payloadKeyFromModelName(modelName) { - return underscore(modelName); - } - }); - ``` - @property modelName - @type String - @readonly - @static - */ - modelName: null, - - /* - These class methods below provide relationship - introspection abilities about relationships. - - A note about the computed properties contained here: - - **These properties are effectively sealed once called for the first time.** - To avoid repeatedly doing expensive iteration over a model's fields, these - values are computed once and then cached for the remainder of the runtime of - your application. - - If your application needs to modify a class after its initial definition - (for example, using `reopen()` to add additional attributes), make sure you - do it before using your model with the store, which uses these properties - extensively. - */ - - /** - For a given relationship name, returns the model type of the relationship. - - For example, if you define a model like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`. - - @method typeForRelationship - @static - @param {String} name the name of the relationship - @param {store} store an instance of DS.Store - @return {DS.Model} the type of the relationship, or undefined - */ - typeForRelationship(name, store) { - let relationship = get(this, 'relationshipsByName').get(name); - return relationship && store.modelFor(relationship.type); - }, - - inverseMap: computed(function() { - return Object.create(null); - }), - - /** - Find the relationship which is the inverse of the one asked for. - - For example, if you define models like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('message') - }); - ``` - - ```app/models/message.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - owner: DS.belongsTo('post') - }); - ``` - - ``` js - store.modelFor('post').inverseFor('comments', store) // { type: App.Message, name: 'owner', kind: 'belongsTo' } - store.modelFor('message').inverseFor('owner', store) // { type: App.Post, name: 'comments', kind: 'hasMany' } - ``` - - @method inverseFor - @static - @param {String} name the name of the relationship - @param {DS.Store} store - @return {Object} the inverse relationship, or null - */ - inverseFor(name, store) { - let inverseMap = get(this, 'inverseMap'); - if (inverseMap[name] !== undefined) { - return inverseMap[name]; - } - - let relationship = get(this, 'relationshipsByName').get(name); - if ( - !relationship || - // populate the cache with a miss entry so we can skip getting and going - // through `relationshipsByName` - (relationship.options && relationship.options.inverse === null) - ) { - return (inverseMap[name] = null); - } - - return (inverseMap[name] = this._findInverseFor(name, store)); - }, - - //Calculate the inverse, ignoring the cache - _findInverseFor(name, store) { - let inverseType = this.typeForRelationship(name, store); - if (!inverseType) { - return null; - } - - let propertyMeta = this.metaForProperty(name); - //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` - let options = propertyMeta.options; - if (options.inverse === null) { - return null; - } - - let inverseName, inverseKind, inverse, inverseOptions; - - //If inverse is specified manually, return the inverse - if (options.inverse) { - inverseName = options.inverse; - inverse = get(inverseType, 'relationshipsByName').get(inverseName); - - assert( - "We found no inverse relationships by the name of '" + - inverseName + - "' on the '" + - inverseType.modelName + - "' model. This is most likely due to a missing attribute on your model definition.", - !isNone(inverse) - ); - - // TODO probably just return the whole inverse here - inverseKind = inverse.kind; - inverseOptions = inverse.options; - } else { - //No inverse was specified manually, we need to use a heuristic to guess one - if (propertyMeta.parentType && propertyMeta.type === propertyMeta.parentType.modelName) { - warn( - `Detected a reflexive relationship by the name of '${name}' without an inverse option. Look at https://guides.emberjs.com/current/models/relationships/#toc_reflexive-relations for how to explicitly specify inverses.`, - false, - { - id: 'ds.model.reflexive-relationship-without-inverse', - } - ); - } - - let possibleRelationships = findPossibleInverses(this, inverseType, name); - - if (possibleRelationships.length === 0) { - return null; - } - - let filteredRelationships = possibleRelationships.filter(possibleRelationship => { - let optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; - return name === optionsForRelationship.inverse; - }); - - assert( - "You defined the '" + - name + - "' relationship on " + - this + - ', but you defined the inverse relationships of type ' + - inverseType.toString() + - ' multiple times. Look at https://guides.emberjs.com/current/models/relationships/#toc_explicit-inverses for how to explicitly specify inverses', - filteredRelationships.length < 2 - ); - - if (filteredRelationships.length === 1) { - possibleRelationships = filteredRelationships; - } - - assert( - "You defined the '" + - name + - "' relationship on " + - this + - ', but multiple possible inverse relationships of type ' + - this + - ' were found on ' + - inverseType + - '. Look at https://guides.emberjs.com/current/models/relationships/#toc_explicit-inverses for how to explicitly specify inverses', - possibleRelationships.length === 1 - ); - - inverseName = possibleRelationships[0].name; - inverseKind = possibleRelationships[0].kind; - inverseOptions = possibleRelationships[0].options; - } - - assert( - `The ${ - inverseType.modelName - }:${inverseName} relationship declares 'inverse: null', but it was resolved as the inverse for ${ - this.modelName - }:${name}.`, - !inverseOptions || inverseOptions.inverse !== null - ); - - return { - type: inverseType, - name: inverseName, - kind: inverseKind, - options: inverseOptions, - }; - }, - - /** - The model's relationships as a map, keyed on the type of the - relationship. The value of each entry is an array containing a descriptor - for each relationship with that type, describing the name of the relationship - as well as the type. - - For example, given the following model definition: - - ```app/models/blog.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - - This computed property would return a map describing these - relationships, like this: - - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - import User from 'app/models/user'; - import Post from 'app/models/post'; - - let relationships = Ember.get(Blog, 'relationships'); - relationships.get(User); - //=> [ { name: 'users', kind: 'hasMany' }, - // { name: 'owner', kind: 'belongsTo' } ] - relationships.get(Post); - //=> [ { name: 'posts', kind: 'hasMany' } ] - ``` - - @property relationships - @static - @type Map - @readOnly - */ - - relationships: relationshipsDescriptor, - - /** - A hash containing lists of the model's relationships, grouped - by the relationship kind. For example, given a model with this - definition: - - ```app/models/blog.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - - let relationshipNames = Ember.get(Blog, 'relationshipNames'); - relationshipNames.hasMany; - //=> ['users', 'posts'] - relationshipNames.belongsTo; - //=> ['owner'] - ``` - - @property relationshipNames - @static - @type Object - @readOnly - */ - relationshipNames: computed(function() { - let names = { - hasMany: [], - belongsTo: [], - }; - - this.eachComputedProperty((name, meta) => { - if (meta.isRelationship) { - names[meta.kind].push(name); - } - }); - - return names; - }), - - /** - An array of types directly related to a model. Each type will be - included once, regardless of the number of relationships it has with - the model. - - For example, given a model with this definition: - - ```app/models/blog.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - - let relatedTypes = Ember.get(Blog, 'relatedTypes'); - //=> [ User, Post ] - ``` - - @property relatedTypes - @static - @type Ember.Array - @readOnly - */ - relatedTypes: relatedTypesDescriptor, - - /** - A map whose keys are the relationships of a model and whose values are - relationship descriptors. - - For example, given a model with this - definition: - - ```app/models/blog.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - - let relationshipsByName = Ember.get(Blog, 'relationshipsByName'); - relationshipsByName.get('users'); - //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true } - relationshipsByName.get('owner'); - //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true } - ``` - - @property relationshipsByName - @static - @type Map - @readOnly - */ - relationshipsByName: relationshipsByNameDescriptor, - - /** - A map whose keys are the fields of the model and whose values are strings - describing the kind of the field. A model's fields are the union of all of its - attributes and relationships. - - For example: - - ```app/models/blog.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post'), - - title: DS.attr('string') - }); - ``` - - ```js - import Ember from 'ember'; - import Blog from 'app/models/blog'; - - let fields = Ember.get(Blog, 'fields'); - fields.forEach(function(kind, field) { - console.log(field, kind); - }); - - // prints: - // users, hasMany - // owner, belongsTo - // posts, hasMany - // title, attribute - ``` - - @property fields - @static - @type Map - @readOnly - */ - fields: computed(function() { - let map = new Map(); - - this.eachComputedProperty((name, meta) => { - if (meta.isRelationship) { - map.set(name, meta.kind); - } else if (meta.isAttribute) { - map.set(name, 'attribute'); - } - }); - - return map; - }).readOnly(), - - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - @method eachRelationship - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship(callback, binding) { - get(this, 'relationshipsByName').forEach((relationship, name) => { - callback.call(binding, name, relationship); - }); - }, - - /** - Given a callback, iterates over each of the types related to a model, - invoking the callback with the related type's class. Each type will be - returned just once, regardless of how many different relationships it has - with a model. - - @method eachRelatedType - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelatedType(callback, binding) { - let relationshipTypes = get(this, 'relatedTypes'); - - for (let i = 0; i < relationshipTypes.length; i++) { - let type = relationshipTypes[i]; - callback.call(binding, type); - } - }, - - determineRelationshipType(knownSide, store) { - let knownKey = knownSide.key; - let knownKind = knownSide.kind; - let inverse = this.inverseFor(knownKey, store); - // let key; - let otherKind; - - if (!inverse) { - return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; - } - - // key = inverse.name; - otherKind = inverse.kind; - - if (otherKind === 'belongsTo') { - return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; - } else { - return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; - } - }, - - /** - A map whose keys are the attributes of the model (properties - described by DS.attr) and whose values are the meta object for the - property. - - Example - - ```app/models/person.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - birthday: DS.attr('date') - }); - ``` - - ```javascript - import Ember from 'ember'; - import Person from 'app/models/person'; - - let attributes = Ember.get(Person, 'attributes') - - attributes.forEach(function(meta, name) { - console.log(name, meta); - }); - - // prints: - // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} - // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} - // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} - ``` - - @property attributes - @static - @type {Map} - @readOnly - */ - attributes: computed(function() { - let map = new Map(); - - this.eachComputedProperty((name, meta) => { - if (meta.isAttribute) { - assert( - "You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + - this.toString(), - name !== 'id' - ); - - meta.name = name; - map.set(name, meta); - } - }); - - return map; - }).readOnly(), - - /** - A map whose keys are the attributes of the model (properties - described by DS.attr) and whose values are type of transformation - applied to each attribute. This map does not include any - attributes that do not have an transformation type. - - Example - - ```app/models/person.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - firstName: DS.attr(), - lastName: DS.attr('string'), - birthday: DS.attr('date') - }); - ``` - - ```javascript - import Ember from 'ember'; - import Person from 'app/models/person'; - - let transformedAttributes = Ember.get(Person, 'transformedAttributes') - - transformedAttributes.forEach(function(field, type) { - console.log(field, type); - }); - - // prints: - // lastName string - // birthday date - ``` - - @property transformedAttributes - @static - @type {Map} - @readOnly - */ - transformedAttributes: computed(function() { - let map = new Map(); - - this.eachAttribute((key, meta) => { - if (meta.type) { - map.set(key, meta.type); - } - }); - - return map; - }).readOnly(), - - /** - Iterates through the attributes of the model, calling the passed function on each - attribute. - - The callback method you provide should have the following signature (all - parameters are optional): - - ```javascript - function(name, meta); - ``` - - - `name` the name of the current property in the iteration - - `meta` the meta object for the attribute property in the iteration - - 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 - - ```javascript - import DS from 'ember-data'; - - let Person = DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - birthday: DS.attr('date') - }); - - Person.eachAttribute(function(name, meta) { - console.log(name, meta); - }); - - // prints: - // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} - // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} - // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} - ``` - - @method eachAttribute - @param {Function} callback The callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - @static - */ - eachAttribute(callback, binding) { - get(this, 'attributes').forEach((meta, name) => { - callback.call(binding, name, meta); - }); - }, - - /** - Iterates through the transformedAttributes of the model, calling - the passed function on each attribute. Note the callback will not be - called for any attributes that do not have an transformation type. - - The callback method you provide should have the following signature (all - parameters are optional): - - ```javascript - function(name, type); - ``` - - - `name` the name of the current property in the iteration - - `type` a string containing the name of the type of transformed - applied to the attribute - - 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 - - ```javascript - import DS from 'ember-data'; - - let Person = DS.Model.extend({ - firstName: DS.attr(), - lastName: DS.attr('string'), - birthday: DS.attr('date') - }); - - Person.eachTransformedAttribute(function(name, type) { - console.log(name, type); - }); - - // prints: - // lastName string - // birthday date - ``` - - @method eachTransformedAttribute - @param {Function} callback The callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - @static - */ - eachTransformedAttribute(callback, binding) { - get(this, 'transformedAttributes').forEach((type, name) => { - callback.call(binding, name, type); - }); - }, - - /** - Returns the name of the model class. - - @method toString - @static - */ - toString() { - return `model:${get(this, 'modelName')}`; - }, -}); - -if (DEBUG) { - Model.reopen({ - // This is a temporary solution until we refactor DS.Model to not - // rely on the data property. - willMergeMixin(props) { - let constructor = this.constructor; - assert( - '`' + - intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + - '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + - constructor.toString(), - !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] - ); - assert( - "You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + - constructor.toString(), - Object.keys(props).indexOf('id') === -1 - ); - }, - - /** - This Ember.js hook allows an object to be notified when a property - is defined. - - In this case, we use it to be notified when an Ember Data user defines a - belongs-to relationship. In that case, we need to set up observers for - each one, allowing us to track relationship changes and automatically - reflect changes in the inverse has-many array. - - This hook passes the class being set up, as well as the key and value - being defined. So, for example, when the user does this: - - ```javascript - DS.Model.extend({ - parent: DS.belongsTo('user') - }); - ``` - - This hook would be called with "parent" as the key and the computed - property returned by `DS.belongsTo` as the value. - - @method didDefineProperty - @param {Object} proto - @param {String} key - @param {Ember.ComputedProperty} value - */ - didDefineProperty(proto, key, value) { - // Check if the value being set is a computed property. - if (value instanceof ComputedProperty) { - // If it is, get the metadata for the relationship. This is - // populated by the `DS.belongsTo` helper when it is creating - // the computed property. - let meta = value.meta(); - - /* - This is buggy because if the parent has never been looked up - via `modelFor` it will not have `modelName` set. - */ - meta.parentType = proto.constructor; - } - }, - }); -} - -export default Model; diff --git a/addon/-legacy-private/system/model/states.js b/addon/-legacy-private/system/model/states.js deleted file mode 100644 index 893a1680a35..00000000000 --- a/addon/-legacy-private/system/model/states.js +++ /dev/null @@ -1,766 +0,0 @@ -/** - @module ember-data -*/ -import { assert } from '@ember/debug'; - -/* - This file encapsulates the various states that a record can transition - through during its lifecycle. -*/ -/** - ### State - - Each record has a `currentState` property that explicitly tracks what - state a record is in at any given time. For instance, if a record is - newly created and has not yet been sent to the adapter to be saved, - it would be in the `root.loaded.created.uncommitted` state. If a - record has had local modifications made to it that are in the - process of being saved, the record would be in the - `root.loaded.updated.inFlight` state. (This state path will be - explained in more detail below.) - - Events are sent by the record or its store to the record's - `currentState` property. How the state reacts to these events is - dependent on which state it is in. In some states, certain events - will be invalid and will cause an exception to be raised. - - States are hierarchical and every state is a sub-state of the - `RootState`. For example, a record can be in the - `root.deleted.uncommitted` state then transitions into the - `root.deleted.inFlight` state. If a child state does not implement - an event handler, the state manager will attempt to invoke the event - on all parent states until the root state is reached. The state - hierarchy of a record is described in terms of a path string. You - can determine a record's current state by getting the state's - `stateName` property: - - ```javascript - record.get('currentState.stateName'); - //=> "root.created.uncommitted" - ``` - - The hierarchy of valid states that ship with ember data looks like - this: - - ```text - * root - * deleted - * saved - * uncommitted - * inFlight - * empty - * loaded - * created - * uncommitted - * inFlight - * saved - * updated - * uncommitted - * inFlight - * loading - ``` - - The `DS.Model` states are themselves stateless. What that means is - that, the hierarchical states that each of *those* points to is a - shared data structure. For performance reasons, instead of each - record getting its own copy of the hierarchy of states, each record - points to this global, immutable shared instance. How does a state - know which record it should be acting on? We pass the record - instance into the state's event handlers as the first argument. - - The record passed as the first parameter is where you should stash - state about the record if needed; you should never store data on the state - object itself. - - ### Events and Flags - - A state may implement zero or more events and flags. - - #### Events - - Events are named functions that are invoked when sent to a record. The - record will first look for a method with the given name on the - current state. If no method is found, it will search the current - state's parent, and then its grandparent, and so on until reaching - the top of the hierarchy. If the root is reached without an event - handler being found, an exception will be raised. This can be very - helpful when debugging new features. - - Here's an example implementation of a state with a `myEvent` event handler: - - ```javascript - aState: DS.State.create({ - myEvent: function(manager, param) { - console.log("Received myEvent with", param); - } - }) - ``` - - To trigger this event: - - ```javascript - record.send('myEvent', 'foo'); - //=> "Received myEvent with foo" - ``` - - Note that an optional parameter can be sent to a record's `send()` method, - which will be passed as the second parameter to the event handler. - - Events should transition to a different state if appropriate. This can be - done by calling the record's `transitionTo()` method with a path to the - desired state. The state manager will attempt to resolve the state path - relative to the current state. If no state is found at that path, it will - attempt to resolve it relative to the current state's parent, and then its - parent, and so on until the root is reached. For example, imagine a hierarchy - like this: - - * created - * uncommitted <-- currentState - * inFlight - * updated - * inFlight - - If we are currently in the `uncommitted` state, calling - `transitionTo('inFlight')` would transition to the `created.inFlight` state, - while calling `transitionTo('updated.inFlight')` would transition to - the `updated.inFlight` state. - - Remember that *only events* should ever cause a state transition. You should - never call `transitionTo()` from outside a state's event handler. If you are - tempted to do so, create a new event and send that to the state manager. - - #### Flags - - Flags are Boolean values that can be used to introspect a record's current - state in a more user-friendly way than examining its state path. For example, - instead of doing this: - - ```javascript - var statePath = record.get('stateManager.currentPath'); - if (statePath === 'created.inFlight') { - doSomething(); - } - ``` - - You can say: - - ```javascript - if (record.get('isNew') && record.get('isSaving')) { - doSomething(); - } - ``` - - If your state does not set a value for a given flag, the value will - be inherited from its parent (or the first place in the state hierarchy - where it is defined). - - The current set of flags are defined below. If you want to add a new flag, - in addition to the area below, you will also need to declare it in the - `DS.Model` class. - - - * [isEmpty](DS.Model.html#property_isEmpty) - * [isLoading](DS.Model.html#property_isLoading) - * [isLoaded](DS.Model.html#property_isLoaded) - * [hasDirtyAttributes](DS.Model.html#property_hasDirtyAttributes) - * [isSaving](DS.Model.html#property_isSaving) - * [isDeleted](DS.Model.html#property_isDeleted) - * [isNew](DS.Model.html#property_isNew) - * [isValid](DS.Model.html#property_isValid) - - @namespace DS - @class RootState -*/ - -function didSetProperty(internalModel, context) { - if (context.value === context.originalValue) { - delete internalModel._attributes[context.name]; - internalModel.send('propertyWasReset', context.name); - } else if (context.value !== context.oldValue) { - internalModel.send('becomeDirty'); - } - - internalModel.updateRecordArrays(); -} - -// Implementation notes: -// -// Each state has a boolean value for all of the following flags: -// -// * isLoaded: The record has a populated `data` property. When a -// record is loaded via `store.find`, `isLoaded` is false -// until the adapter sets it. When a record is created locally, -// its `isLoaded` property is always true. -// * isDirty: The record has local changes that have not yet been -// saved by the adapter. This includes records that have been -// created (but not yet saved) or deleted. -// * isSaving: The record has been committed, but -// the adapter has not yet acknowledged that the changes have -// been persisted to the backend. -// * isDeleted: The record was marked for deletion. When `isDeleted` -// is true and `isDirty` is true, the record is deleted locally -// but the deletion was not yet persisted. When `isSaving` is -// true, the change is in-flight. When both `isDirty` and -// `isSaving` are false, the change has persisted. -// * isNew: The record was created on the client and the adapter -// did not yet report that it was successfully saved. -// * isValid: The adapter did not report any server-side validation -// failures. - -// The dirty state is a abstract state whose functionality is -// shared between the `created` and `updated` states. -// -// The deleted state shares the `isDirty` flag with the -// subclasses of `DirtyState`, but with a very different -// implementation. -// -// Dirty states have three child states: -// -// `uncommitted`: the store has not yet handed off the record -// to be saved. -// `inFlight`: the store has handed off the record to be saved, -// but the adapter has not yet acknowledged success. -// `invalid`: the record has invalid information and cannot be -// sent to the adapter yet. -const DirtyState = { - initialState: 'uncommitted', - - // FLAGS - isDirty: true, - - // SUBSTATES - - // When a record first becomes dirty, it is `uncommitted`. - // This means that there are local pending changes, but they - // have not yet begun to be saved, and are not invalid. - uncommitted: { - // EVENTS - didSetProperty, - - //TODO(Igor) reloading now triggers a - //loadingData event, though it seems fine? - loadingData() {}, - - propertyWasReset(internalModel, name) { - if (!internalModel.hasChangedAttributes()) { - internalModel.send('rolledBack'); - } - }, - - pushedData(internalModel) { - let token = heimdall.start('stats.uncommitted.pushedData'); - internalModel.updateChangedAttributes(); - - if (!internalModel.hasChangedAttributes()) { - internalModel.transitionTo('loaded.saved'); - } - heimdall.stop(token); - }, - - becomeDirty() {}, - - willCommit(internalModel) { - internalModel.transitionTo('inFlight'); - }, - - reloadRecord(internalModel, { resolve, options }) { - resolve(internalModel.store._reloadRecord(internalModel, options)); - }, - - rolledBack(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('rolledBack'); - }, - - becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - }, - - rollback(internalModel) { - internalModel.rollbackAttributes(); - internalModel.triggerLater('ready'); - }, - }, - - // Once a record has been handed off to the adapter to be - // saved, it is in the 'in flight' state. Changes to the - // record cannot be made during this window. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - didSetProperty, - becomeDirty() {}, - pushedData() {}, - - unloadRecord: assertAgainstUnloadRecord, - - // TODO: More robust semantics around save-while-in-flight - willCommit() {}, - - didCommit(internalModel) { - internalModel.transitionTo('saved'); - internalModel.send('invokeLifecycleCallbacks', this.dirtyType); - }, - - rolledBack(internalModel) { - internalModel.triggerLater('rolledBack'); - }, - - becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - internalModel.send('invokeLifecycleCallbacks'); - }, - - becameError(internalModel) { - internalModel.transitionTo('uncommitted'); - internalModel.triggerLater('becameError', internalModel); - }, - }, - - // A record is in the `invalid` if the adapter has indicated - // the the record failed server-side invalidations. - invalid: { - // FLAGS - isValid: false, - - // EVENTS - deleteRecord(internalModel) { - internalModel.transitionTo('deleted.uncommitted'); - }, - - didSetProperty(internalModel, context) { - internalModel.removeErrorMessageFromAttribute(context.name); - - didSetProperty(internalModel, context); - - if (!internalModel.hasErrors()) { - this.becameValid(internalModel); - } - }, - - becameInvalid() {}, - becomeDirty() {}, - pushedData() {}, - - willCommit(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('inFlight'); - }, - - rolledBack(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - }, - - becameValid(internalModel) { - internalModel.transitionTo('uncommitted'); - }, - - invokeLifecycleCallbacks(internalModel) { - internalModel.triggerLater('becameInvalid', internalModel); - }, - }, -}; - -// The created and updated states are created outside the state -// chart so we can reopen their substates and add mixins as -// necessary. - -function deepClone(object) { - const clone = {}; - let value; - - for (let prop in object) { - value = object[prop]; - if (value && typeof value === 'object') { - clone[prop] = deepClone(value); - } else { - clone[prop] = value; - } - } - - return clone; -} - -function mixin(original, hash) { - for (let prop in hash) { - original[prop] = hash[prop]; - } - - return original; -} - -function dirtyState(options) { - var newState = deepClone(DirtyState); - return mixin(newState, options); -} - -const createdState = dirtyState({ - dirtyType: 'created', - // FLAGS - isNew: true, -}); - -createdState.invalid.rolledBack = function(internalModel) { - internalModel.transitionTo('deleted.saved'); - internalModel.triggerLater('rolledBack'); -}; - -createdState.uncommitted.rolledBack = function(internalModel) { - internalModel.transitionTo('deleted.saved'); - internalModel.triggerLater('rolledBack'); -}; - -const updatedState = dirtyState({ - dirtyType: 'updated', -}); - -function createdStateDeleteRecord(internalModel) { - internalModel.transitionTo('deleted.saved'); - internalModel.send('invokeLifecycleCallbacks'); -} - -createdState.uncommitted.deleteRecord = createdStateDeleteRecord; - -createdState.invalid.deleteRecord = createdStateDeleteRecord; - -createdState.uncommitted.rollback = function(internalModel) { - DirtyState.uncommitted.rollback.apply(this, arguments); - internalModel.transitionTo('deleted.saved'); -}; - -createdState.uncommitted.pushedData = function(internalModel) { - internalModel.transitionTo('loaded.updated.uncommitted'); - internalModel.triggerLater('didLoad'); -}; - -createdState.uncommitted.propertyWasReset = function() {}; - -function assertAgainstUnloadRecord(internalModel) { - assert('You can only unload a record which is not inFlight. `' + internalModel + '`', false); -} - -updatedState.invalid.becameValid = function(internalModel) { - // we're eagerly transition into the loaded.saved state, even though we could - // be still dirty; but the setup hook of the loaded.saved state checks for - // dirty attributes and transitions into the corresponding dirty state - internalModel.transitionTo('loaded.saved'); -}; - -updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; - -updatedState.uncommitted.deleteRecord = function(internalModel) { - internalModel.transitionTo('deleted.uncommitted'); -}; - -updatedState.invalid.rolledBack = function(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('rolledBack'); -}; - -const RootState = { - // FLAGS - isEmpty: false, - isLoading: false, - isLoaded: false, - isDirty: false, - isSaving: false, - isDeleted: false, - isNew: false, - isValid: true, - - // DEFAULT EVENTS - - // Trying to roll back if you're not in the dirty state - // doesn't change your state. For example, if you're in the - // in-flight state, rolling back the record doesn't move - // you out of the in-flight state. - rolledBack() {}, - unloadRecord(internalModel) {}, - - propertyWasReset() {}, - - // SUBSTATES - - // A record begins its lifecycle in the `empty` state. - // If its data will come from the adapter, it will - // transition into the `loading` state. Otherwise, if - // the record is being created on the client, it will - // transition into the `created` state. - empty: { - isEmpty: true, - - // EVENTS - loadingData(internalModel, promise) { - internalModel._promiseProxy = promise; - internalModel.transitionTo('loading'); - }, - - loadedData(internalModel) { - internalModel.transitionTo('loaded.created.uncommitted'); - internalModel.triggerLater('ready'); - }, - - pushedData(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('didLoad'); - internalModel.triggerLater('ready'); - }, - }, - - // A record enters this state when the store asks - // the adapter for its data. It remains in this state - // until the adapter provides the requested data. - // - // Usually, this process is asynchronous, using an - // XHR to retrieve the data. - loading: { - // FLAGS - isLoading: true, - - exit(internalModel) { - internalModel._promiseProxy = null; - }, - - // EVENTS - pushedData(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('didLoad'); - internalModel.triggerLater('ready'); - //TODO this seems out of place here - internalModel.didCleanError(); - }, - - becameError(internalModel) { - internalModel.triggerLater('becameError', internalModel); - }, - - notFound(internalModel) { - internalModel.transitionTo('empty'); - }, - }, - - // A record enters this state when its data is populated. - // Most of a record's lifecycle is spent inside substates - // of the `loaded` state. - loaded: { - initialState: 'saved', - - // FLAGS - isLoaded: true, - - //TODO(Igor) Reloading now triggers a loadingData event, - //but it should be ok? - loadingData() {}, - - // SUBSTATES - - // If there are no local changes to a record, it remains - // in the `saved` state. - saved: { - setup(internalModel) { - if (internalModel.hasChangedAttributes()) { - internalModel.adapterDidDirty(); - } - }, - - // EVENTS - didSetProperty, - - pushedData() {}, - - becomeDirty(internalModel) { - internalModel.transitionTo('updated.uncommitted'); - }, - - willCommit(internalModel) { - internalModel.transitionTo('updated.inFlight'); - }, - - reloadRecord(internalModel, { resolve, options }) { - resolve(internalModel.store._reloadRecord(internalModel, options)); - }, - - deleteRecord(internalModel) { - internalModel.transitionTo('deleted.uncommitted'); - }, - - unloadRecord(internalModel) {}, - - didCommit() {}, - - // loaded.saved.notFound would be triggered by a failed - // `reload()` on an unchanged record - notFound() {}, - }, - - // A record is in this state after it has been locally - // created but before the adapter has indicated that - // it has been saved. - created: createdState, - - // A record is in this state if it has already been - // saved to the server, but there are new local changes - // that have not yet been saved. - updated: updatedState, - }, - - // A record is in this state if it was deleted from the store. - deleted: { - initialState: 'uncommitted', - dirtyType: 'deleted', - - // FLAGS - isDeleted: true, - isLoaded: true, - isDirty: true, - - // TRANSITIONS - setup(internalModel) { - internalModel.updateRecordArrays(); - }, - - // SUBSTATES - - // When a record is deleted, it enters the `start` - // state. It will exit this state when the record - // starts to commit. - uncommitted: { - // EVENTS - - willCommit(internalModel) { - internalModel.transitionTo('inFlight'); - }, - - rollback(internalModel) { - internalModel.rollbackAttributes(); - internalModel.triggerLater('ready'); - }, - - pushedData() {}, - becomeDirty() {}, - deleteRecord() {}, - - rolledBack(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - internalModel.triggerLater('rolledBack'); - }, - }, - - // After a record starts committing, but - // before the adapter indicates that the deletion - // has saved to the server, a record is in the - // `inFlight` substate of `deleted`. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - - unloadRecord: assertAgainstUnloadRecord, - - // TODO: More robust semantics around save-while-in-flight - willCommit() {}, - didCommit(internalModel) { - internalModel.transitionTo('saved'); - - internalModel.send('invokeLifecycleCallbacks'); - }, - - becameError(internalModel) { - internalModel.transitionTo('uncommitted'); - internalModel.triggerLater('becameError', internalModel); - }, - - becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - internalModel.triggerLater('becameInvalid', internalModel); - }, - }, - - // Once the adapter indicates that the deletion has - // been saved, the record enters the `saved` substate - // of `deleted`. - saved: { - // FLAGS - isDirty: false, - - setup(internalModel) { - internalModel.removeFromInverseRelationships(); - }, - - invokeLifecycleCallbacks(internalModel) { - internalModel.triggerLater('didDelete', internalModel); - internalModel.triggerLater('didCommit', internalModel); - }, - - willCommit() {}, - didCommit() {}, - pushedData() {}, - }, - - invalid: { - isValid: false, - - didSetProperty(internalModel, context) { - internalModel.removeErrorMessageFromAttribute(context.name); - - didSetProperty(internalModel, context); - - if (!internalModel.hasErrors()) { - this.becameValid(internalModel); - } - }, - - becameInvalid() {}, - becomeDirty() {}, - deleteRecord() {}, - willCommit() {}, - - rolledBack(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - }, - - becameValid(internalModel) { - internalModel.transitionTo('uncommitted'); - }, - }, - }, - - invokeLifecycleCallbacks(internalModel, dirtyType) { - if (dirtyType === 'created') { - internalModel.triggerLater('didCreate', internalModel); - } else { - internalModel.triggerLater('didUpdate', internalModel); - } - - internalModel.triggerLater('didCommit', internalModel); - }, -}; - -function wireState(object, parent, name) { - // TODO: Use Object.create and copy instead - object = mixin(parent ? Object.create(parent) : {}, object); - object.parentState = parent; - object.stateName = name; - - for (let prop in object) { - if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { - continue; - } - if (typeof object[prop] === 'object') { - object[prop] = wireState(object[prop], object, name + '.' + prop); - } - } - - return object; -} - -export default wireState(RootState, null, 'root'); diff --git a/addon/-legacy-private/system/promise-proxies.js b/addon/-legacy-private/system/promise-proxies.js deleted file mode 100644 index 4a419ac7a01..00000000000 --- a/addon/-legacy-private/system/promise-proxies.js +++ /dev/null @@ -1,162 +0,0 @@ -import ObjectProxy from '@ember/object/proxy'; -import PromiseProxyMixin from '@ember/object/promise-proxy-mixin'; -import ArrayProxy from '@ember/array/proxy'; -import { get, computed } from '@ember/object'; -import { reads } from '@ember/object/computed'; -import { Promise } from 'rsvp'; -import { assert } from '@ember/debug'; - -/** - A `PromiseArray` is an object that acts like both an `Ember.Array` - and a promise. When the promise is resolved the resulting value - will be set to the `PromiseArray`'s `content` property. This makes - it easy to create data bindings with the `PromiseArray` that will be - updated when the promise resolves. - - For more information see the [Ember.PromiseProxyMixin - documentation](/api/classes/Ember.PromiseProxyMixin.html). - - Example - - ```javascript - let promiseArray = DS.PromiseArray.create({ - promise: $.getJSON('/some/remote/data.json') - }); - - promiseArray.get('length'); // 0 - - promiseArray.then(function() { - promiseArray.get('length'); // 100 - }); - ``` - - @class PromiseArray - @namespace DS - @extends Ember.ArrayProxy - @uses Ember.PromiseProxyMixin -*/ -export const PromiseArray = ArrayProxy.extend(PromiseProxyMixin, { - meta: reads('content.meta'), -}); - -/** - A `PromiseObject` is an object that acts like both an `Ember.Object` - and a promise. When the promise is resolved, then the resulting value - will be set to the `PromiseObject`'s `content` property. This makes - it easy to create data bindings with the `PromiseObject` that will - be updated when the promise resolves. - - For more information see the [Ember.PromiseProxyMixin - documentation](/api/classes/Ember.PromiseProxyMixin.html). - - Example - - ```javascript - let promiseObject = DS.PromiseObject.create({ - promise: $.getJSON('/some/remote/data.json') - }); - - promiseObject.get('name'); // null - - promiseObject.then(function() { - promiseObject.get('name'); // 'Tomster' - }); - ``` - - @class PromiseObject - @namespace DS - @extends Ember.ObjectProxy - @uses Ember.PromiseProxyMixin -*/ -export let PromiseObject = ObjectProxy.extend(PromiseProxyMixin); - -export function promiseObject(promise, label) { - return PromiseObject.create({ - promise: Promise.resolve(promise, label), - }); -} - -export function promiseArray(promise, label) { - return PromiseArray.create({ - promise: Promise.resolve(promise, label), - }); -} - -export const PromiseBelongsTo = PromiseObject.extend({ - // we don't proxy meta because we would need to proxy it to the relationship state container - // however, meta on relationships does not trigger change notifications. - // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()` - meta: computed(function() { - assert( - 'You attempted to access meta on the promise for the async belongsTo relationship ' + - `${this.get('_belongsToState').internalModel.modelName}:${ - this.get('_belongsToState').key - }'.` + - '\nUse `record.belongsTo(relationshipName).meta()` instead.', - false - ); - }), - - reload() { - assert( - 'You are trying to reload an async belongsTo before it has been created', - this.get('content') !== undefined - ); - this.get('_belongsToState').reload(); - - return this; - }, -}); - -/** - A PromiseManyArray is a PromiseArray that also proxies certain method calls - to the underlying manyArray. - Right now we proxy: - - * `reload()` - * `createRecord()` - * `on()` - * `one()` - * `trigger()` - * `off()` - * `has()` - - @class PromiseManyArray - @namespace DS - @extends Ember.ArrayProxy -*/ - -export function proxyToContent(method) { - return function() { - return get(this, 'content')[method](...arguments); - }; -} - -export const PromiseManyArray = PromiseArray.extend({ - reload() { - assert( - 'You are trying to reload an async manyArray before it has been created', - get(this, 'content') - ); - this.set('promise', this.get('content').reload()); - return this; - }, - - createRecord: proxyToContent('createRecord'), - - on: proxyToContent('on'), - - one: proxyToContent('one'), - - trigger: proxyToContent('trigger'), - - off: proxyToContent('off'), - - has: proxyToContent('has'), -}); - -export function promiseManyArray(promise, label) { - return PromiseManyArray.create({ - promise: Promise.resolve(promise, label), - }); -} diff --git a/addon/-legacy-private/system/references/belongs-to.js b/addon/-legacy-private/system/references/belongs-to.js deleted file mode 100644 index 1506b1d2d39..00000000000 --- a/addon/-legacy-private/system/references/belongs-to.js +++ /dev/null @@ -1,440 +0,0 @@ -import { resolve } from 'rsvp'; -import Model from '../model/model'; -import Reference from './reference'; - -import { assertPolymorphicType } from 'ember-data/-debug'; - -/** - A BelongsToReference is a low-level API that allows users and - addon author to perform meta-operations on a belongs-to - relationship. - - @class BelongsToReference - @namespace DS - @extends DS.Reference -*/ -export default class BelongsToReference extends Reference { - constructor(store, parentInternalModel, belongsToRelationship) { - super(store, parentInternalModel); - this.belongsToRelationship = belongsToRelationship; - this.type = belongsToRelationship.relationshipMeta.type; - this.parent = parentInternalModel.recordReference; - // TODO inverse - } - - /** - This returns a string that represents how the reference will be - looked up when it is loaded. If the relationship has a link it will - use the "link" otherwise it defaults to "id". - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - }); - let userRef = blog.belongsTo('user'); - - // get the identifier of the reference - if (userRef.remoteType() === "id") { - let id = userRef.id(); - } else if (userRef.remoteType() === "link") { - let link = userRef.link(); - } - ``` - - @method remoteType - @return {String} The name of the remote type. This should either be "link" or "id" - */ - remoteType() { - if (this.belongsToRelationship.link) { - return 'link'; - } - - return 'id'; - } - - /** - The `id` of the record that this reference refers to. Together, the - `type()` and `id()` methods form a composite key for the identity - map. This can be used to access the id of an async relationship - without triggering a fetch that would normally happen if you - attempted to use `record.get('relationship.id')`. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - // get the identifier of the reference - if (userRef.remoteType() === "id") { - let id = userRef.id(); - } - ``` - - @method id - @return {String} The id of the record in this belongsTo relationship. - */ - id() { - let inverseInternalModel = this.belongsToRelationship.inverseInternalModel; - return inverseInternalModel && inverseInternalModel.id; - } - - /** - The link Ember Data will use to fetch or reload this belongs-to - relationship. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - links: { - related: '/articles/1/author' - } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - // get the identifier of the reference - if (userRef.remoteType() === "link") { - let link = userRef.link(); - } - ``` - - @method link - @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship. - */ - link() { - return this.belongsToRelationship.link; - } - - /** - The meta data for the belongs-to relationship. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - links: { - related: { - href: '/articles/1/author', - meta: { - lastUpdated: 1458014400000 - } - } - } - } - } - } - }); - - let userRef = blog.belongsTo('user'); - - userRef.meta() // { lastUpdated: 1458014400000 } - ``` - - @method meta - @return {Object} The meta information for the belongs-to relationship. - */ - meta() { - return this.belongsToRelationship.meta; - } - - /** - `push` can be used to update the data in the relationship and Ember - Data will treat the new data as the conanical value of this - relationship on the backend. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - // provide data for reference - userRef.push({ - data: { - type: 'user', - id: 1, - attributes: { - username: "@user" - } - } - }).then(function(user) { - userRef.value() === user; - }); - ``` - - @method push - @param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. - @return {Promise} A promise that resolves with the new value in this belongs-to relationship. - */ - push(objectOrPromise) { - return resolve(objectOrPromise).then(data => { - let record; - - if (data instanceof Model) { - record = data; - } else { - record = this.store.push(data); - } - - assertPolymorphicType( - this.internalModel, - this.belongsToRelationship.relationshipMeta, - record._internalModel, - this.store - ); - - this.belongsToRelationship.setCanonicalInternalModel(record._internalModel); - - return record; - }); - } - - /** - `value()` synchronously returns the current value of the belongs-to - relationship. Unlike `record.get('relationshipName')`, calling - `value()` on a reference does not trigger a fetch if the async - relationship is not yet loaded. If the relationship is not loaded - it will always return `null`. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - userRef.value(); // null - - // provide data for reference - userRef.push({ - data: { - type: 'user', - id: 1, - attributes: { - username: "@user" - } - } - }).then(function(user) { - userRef.value(); // user - }); - ``` - - @method value - @return {DS.Model} the record in this relationship - */ - value() { - let inverseInternalModel = this.belongsToRelationship.inverseInternalModel; - - if (inverseInternalModel && inverseInternalModel.isLoaded()) { - return inverseInternalModel.getRecord(); - } - - return null; - } - - /** - Loads a record in a belongs to-relationship if it is not already - loaded. If the relationship is already loaded this method does not - trigger a new load. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - userRef.value(); // null - - userRef.load().then(function(user) { - userRef.value() === user - }); - ``` - - You may also pass in an options object whose properties will be - fed forward. This enables you to pass `adapterOptions` into the - request given to the adapter via the reference. - - Example - - ```javascript - userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) { - userRef.value() === user; - }); - ``` - - ```app/adapters/user.js - export default ApplicationAdapter.extend({ - findRecord(store, type, id, snapshot) { - // In the adapter you will have access to adapterOptions. - let adapterOptions = snapshot.adapterOptions; - } - }); - ``` - - @method load - @param {Object} options the options to pass in. - @return {Promise} a promise that resolves with the record in this belongs-to relationship. - */ - load(options) { - let rel = this.belongsToRelationship; - - rel.getData(options); - - if (rel.fetchPromise !== null) { - return rel.fetchPromise.then(() => { - return this.value(); - }); - } - - return resolve(this.value()); - } - - /** - Triggers a reload of the value in this relationship. If the - remoteType is `"link"` Ember Data will use the relationship link to - reload the relationship. Otherwise, it will reload the record by its - id. - - Example - - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - - let blog = store.push({ - data: { - type: 'blog', - id: 1, - relationships: { - user: { - data: { type: 'user', id: 1 } - } - } - } - }); - let userRef = blog.belongsTo('user'); - - userRef.reload().then(function(user) { - userRef.value() === user - }); - ``` - - You may also pass in an options object whose properties will be - fed forward. This enables you to pass `adapterOptions` into the - request given to the adapter via the reference. A full example - can be found in the `load` method. - - Example - - ```javascript - userRef.reload({ adapterOptions: { isPrivate: true } }) - ``` - - @method reload - @param {Object} options the options to pass in. - @return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed. - */ - reload(options) { - return this.belongsToRelationship.reload(options).then(internalModel => { - return this.value(); - }); - } -} diff --git a/addon/-legacy-private/system/references/has-many.js b/addon/-legacy-private/system/references/has-many.js deleted file mode 100644 index 8201e03fed0..00000000000 --- a/addon/-legacy-private/system/references/has-many.js +++ /dev/null @@ -1,442 +0,0 @@ -import { resolve } from 'rsvp'; -import { get } from '@ember/object'; -import Reference from './reference'; -import { DEBUG } from '@glimmer/env'; -import { assertPolymorphicType } from 'ember-data/-debug'; - -/** - A HasManyReference is a low-level API that allows users and addon - author to perform meta-operations on a has-many relationship. - - @class HasManyReference - @namespace DS -*/ -export default class HasManyReference extends Reference { - constructor(store, parentInternalModel, hasManyRelationship) { - super(store, parentInternalModel); - this.hasManyRelationship = hasManyRelationship; - this.type = hasManyRelationship.relationshipMeta.type; - this.parent = parentInternalModel.recordReference; - // TODO inverse - } - - /** - This returns a string that represents how the reference will be - looked up when it is loaded. If the relationship has a link it will - use the "link" otherwise it defaults to "id". - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - // get the identifier of the reference - if (commentsRef.remoteType() === "ids") { - let ids = commentsRef.ids(); - } else if (commentsRef.remoteType() === "link") { - let link = commentsRef.link(); - } - ``` - - @method remoteType - @return {String} The name of the remote type. This should either be "link" or "ids" - */ - remoteType() { - if (this.hasManyRelationship.link) { - return 'link'; - } - - return 'ids'; - } - - /** - The link Ember Data will use to fetch or reload this has-many - relationship. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - links: { - related: '/posts/1/comments' - } - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.link(); // '/posts/1/comments' - ``` - - @method link - @return {String} The link Ember Data will use to fetch or reload this has-many relationship. - */ - link() { - return this.hasManyRelationship.link; - } - - /** - `ids()` returns an array of the record IDs in this relationship. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.ids(); // ['1'] - ``` - - @method ids - @return {Array} The ids in this has-many relationship - */ - ids() { - let members = this.hasManyRelationship.members.toArray(); - - return members.map(function(internalModel) { - return internalModel.id; - }); - } - - /** - The metadata for the has-many relationship. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - links: { - related: { - href: '/posts/1/comments', - meta: { - count: 10 - } - } - } - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.meta(); // { count: 10 } - ``` - - @method meta - @return {Object} The meta information for the has-many relationship. - */ - meta() { - return this.hasManyRelationship.meta; - } - - /** - `push` can be used to update the data in the relationship and Ember - Data will treat the new data as the canonical value of this - relationship on the backend. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ``` - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.ids(); // ['1'] - - commentsRef.push([ - [{ type: 'comment', id: 2 }], - [{ type: 'comment', id: 3 }], - ]) - - commentsRef.ids(); // ['2', '3'] - ``` - - @method push - @param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. - @return {DS.ManyArray} - */ - push(objectOrPromise) { - return resolve(objectOrPromise).then(payload => { - let array = payload; - - if (typeof payload === 'object' && payload.data) { - array = payload.data; - } - - let internalModels; - internalModels = array.map(obj => { - let record = this.store.push(obj); - - if (DEBUG) { - let relationshipMeta = this.hasManyRelationship.relationshipMeta; - assertPolymorphicType( - this.internalModel, - relationshipMeta, - record._internalModel, - this.store - ); - } - - return record._internalModel; - }); - - this.hasManyRelationship.computeChanges(internalModels); - - return this.hasManyRelationship.manyArray; - }); - } - - _isLoaded() { - let hasRelationshipDataProperty = get(this.hasManyRelationship, 'hasAnyRelationshipData'); - if (!hasRelationshipDataProperty) { - return false; - } - - let members = this.hasManyRelationship.members.toArray(); - - return members.every(function(internalModel) { - return internalModel.isLoaded() === true; - }); - } - - /** - `value()` synchronously returns the current value of the has-many - relationship. Unlike `record.get('relationshipName')`, calling - `value()` on a reference does not trigger a fetch if the async - relationship is not yet loaded. If the relationship is not loaded - it will always return `null`. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - post.get('comments').then(function(comments) { - commentsRef.value() === comments - }) - ``` - - @method value - @return {DS.ManyArray} - */ - value() { - if (this._isLoaded()) { - return this.hasManyRelationship.manyArray; - } - - return null; - } - - /** - Loads the relationship if it is not already loaded. If the - relationship is already loaded this method does not trigger a new - load. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.load().then(function(comments) { - //... - }); - ``` - - You may also pass in an options object whose properties will be - fed forward. This enables you to pass `adapterOptions` into the - request given to the adapter via the reference. - - Example - - ```javascript - commentsRef.load({ adapterOptions: { isPrivate: true } }) - .then(function(comments) { - //... - }); - ``` - - ```app/adapters/comment.js - export default ApplicationAdapter.extend({ - findMany(store, type, id, snapshots) { - // In the adapter you will have access to adapterOptions. - let adapterOptions = snapshots[0].adapterOptions; - } - }); - ``` - - @method load - @param {Object} options the options to pass in. - @return {Promise} a promise that resolves with the ManyArray in - this has-many relationship. - */ - load(options) { - // TODO this can be simplified - if (!this._isLoaded()) { - return this.hasManyRelationship.getData(options); - } - - return resolve(this.hasManyRelationship.manyArray); - } - - /** - Reloads this has-many relationship. - - Example - - ```app/models/post.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - ``` - - ```javascript - let post = store.push({ - data: { - type: 'post', - id: 1, - relationships: { - comments: { - data: [{ type: 'comment', id: 1 }] - } - } - } - }); - - let commentsRef = post.hasMany('comments'); - - commentsRef.reload().then(function(comments) { - //... - }); - ``` - - You may also pass in an options object whose properties will be - fed forward. This enables you to pass `adapterOptions` into the - request given to the adapter via the reference. A full example - can be found in the `load` method. - - Example - - ```javascript - commentsRef.reload({ adapterOptions: { isPrivate: true } }) - ``` - - @method reload - @param {Object} options the options to pass in. - @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. - */ - reload(options) { - return this.hasManyRelationship.reload(options); - } -} diff --git a/addon/-legacy-private/system/references/reference.js b/addon/-legacy-private/system/references/reference.js deleted file mode 100644 index bdf669d3ae4..00000000000 --- a/addon/-legacy-private/system/references/reference.js +++ /dev/null @@ -1,10 +0,0 @@ -var Reference = function(store, internalModel) { - this.store = store; - this.internalModel = internalModel; -}; - -Reference.prototype = { - constructor: Reference, -}; - -export default Reference; diff --git a/addon/-legacy-private/system/relationships/belongs-to.js b/addon/-legacy-private/system/relationships/belongs-to.js deleted file mode 100644 index 155551c025b..00000000000 --- a/addon/-legacy-private/system/relationships/belongs-to.js +++ /dev/null @@ -1,143 +0,0 @@ -import { computed } from '@ember/object'; -import { assert, warn, inspect } from '@ember/debug'; -import normalizeModelName from '../normalize-model-name'; - -/** - `DS.belongsTo` is used to define One-To-One and One-To-Many - relationships on a [DS.Model](/api/data/classes/DS.Model.html). - - - `DS.belongsTo` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a - related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) - - #### One-To-One - To declare a one-to-one relationship between two models, use - `DS.belongsTo`: - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - profile: DS.belongsTo('profile') - }); - ``` - - ```app/models/profile.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - user: DS.belongsTo('user') - }); - ``` - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - You can avoid passing a string as the first parameter. In that case Ember Data - will infer the type from the key name. - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo() - }); - ``` - - will lookup for a Post type. - - @namespace - @method belongsTo - @for DS - @param {String} modelName (optional) type of the relationship - @param {Object} options (optional) a hash of options - @return {Ember.computed} relationship -*/ -export default function belongsTo(modelName, options) { - let opts, userEnteredModelName; - if (typeof modelName === 'object') { - opts = modelName; - userEnteredModelName = undefined; - } else { - opts = options; - userEnteredModelName = modelName; - } - - if (typeof userEnteredModelName === 'string') { - userEnteredModelName = normalizeModelName(userEnteredModelName); - } - - assert( - 'The first argument to DS.belongsTo must be a string representing a model type key, not an instance of ' + - inspect(userEnteredModelName) + - ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", - typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined' - ); - - opts = opts || {}; - - let meta = { - type: userEnteredModelName, - isRelationship: true, - options: opts, - kind: 'belongsTo', - name: 'Belongs To', - key: null, - }; - - return computed({ - get(key) { - if (opts.hasOwnProperty('serialize')) { - warn( - `You provided a serialize option on the "${key}" property in the "${ - this._internalModel.modelName - }" class, this belongs in the serializer. See DS.Serializer and it's implementations https://emberjs.com/api/data/classes/DS.Serializer.html`, - false, - { - id: 'ds.model.serialize-option-in-belongs-to', - } - ); - } - - if (opts.hasOwnProperty('embedded')) { - warn( - `You provided an embedded option on the "${key}" property in the "${ - this._internalModel.modelName - }" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin https://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html`, - false, - { - id: 'ds.model.embedded-option-in-belongs-to', - } - ); - } - - return this._internalModel._relationships.get(key).getData(); - }, - set(key, value) { - this._internalModel.setDirtyBelongsTo(key, value); - - return this._internalModel._relationships.get(key).getData(); - }, - }).meta(meta); -} diff --git a/addon/-legacy-private/system/relationships/ext.js b/addon/-legacy-private/system/relationships/ext.js deleted file mode 100644 index d35608b5583..00000000000 --- a/addon/-legacy-private/system/relationships/ext.js +++ /dev/null @@ -1,70 +0,0 @@ -import { A } from '@ember/array'; -import { computed, get } from '@ember/object'; -import MapWithDefault from '../map-with-default'; -import Map from '../map'; -import { assert } from '@ember/debug'; -import { typeForRelationshipMeta, relationshipFromMeta } from '../relationship-meta'; - -export const relationshipsDescriptor = computed(function() { - let map = new MapWithDefault({ - defaultValue() { - return []; - }, - }); - - let relationshipsByName = get(this, 'relationshipsByName'); - - // Loop through each computed property on the class - relationshipsByName.forEach(desc => { - let relationshipsForType = map.get(desc.type); - relationshipsForType.push(desc); - }); - - return map; -}).readOnly(); - -export const relatedTypesDescriptor = computed(function() { - let modelName; - let types = A(); - - // Loop through each computed property on the class, - // and create an array of the unique types involved - // in relationships - this.eachComputedProperty((name, meta) => { - if (meta.isRelationship) { - meta.key = name; - modelName = typeForRelationshipMeta(meta); - - assert( - `You specified a hasMany (${meta.type}) on ${meta.parentType} but ${ - meta.type - } was not found.`, - modelName - ); - - if (!types.includes(modelName)) { - assert( - `Trying to sideload ${name} on ${this.toString()} but the type doesn't exist.`, - !!modelName - ); - types.push(modelName); - } - } - }); - - return types; -}).readOnly(); - -export const relationshipsByNameDescriptor = computed(function() { - let map = new Map(); - - this.eachComputedProperty((name, meta) => { - if (meta.isRelationship) { - meta.key = name; - meta.name = name; - map.set(name, relationshipFromMeta(meta)); - } - }); - - return map; -}).readOnly(); diff --git a/addon/-legacy-private/system/relationships/has-many.js b/addon/-legacy-private/system/relationships/has-many.js deleted file mode 100644 index e64d566ff08..00000000000 --- a/addon/-legacy-private/system/relationships/has-many.js +++ /dev/null @@ -1,156 +0,0 @@ -/** - @module ember-data -*/ -import { computed } from '@ember/object'; -import { assert, inspect } from '@ember/debug'; -import normalizeModelName from '../normalize-model-name'; - -/** - `DS.hasMany` is used to define One-To-Many and Many-To-Many - relationships on a [DS.Model](/api/data/classes/DS.Model.html). - - `DS.hasMany` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a related model. - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - #### Many-To-Many - To declare a many-to-many relationship between two models, use - `DS.hasMany`: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - tags: DS.hasMany('tag') - }); - ``` - - ```app/models/tag.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - posts: DS.hasMany('post') - }); - ``` - - You can avoid passing a string as the first parameter. In that case Ember Data - will infer the type from the singularized key name. - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - tags: DS.hasMany() - }); - ``` - - will lookup for a Tag type. - - #### Explicit Inverses - - Ember Data will do its best to discover which relationships map to - one another. In the one-to-many code above, for example, Ember Data - can figure out that changing the `comments` relationship should update - the `post` relationship on the inverse because post is the only - relationship to that model. - - However, sometimes you may have multiple `belongsTo`/`hasMany` for the - same type. You can specify which property on the related model is - the inverse using `DS.hasMany`'s `inverse` option: - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - onePost: DS.belongsTo('post'), - twoPost: DS.belongsTo('post'), - redPost: DS.belongsTo('post'), - bluePost: DS.belongsTo('post') - }); - ``` - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment', { - inverse: 'redPost' - }) - }); - ``` - - You can also specify an inverse on a `belongsTo`, which works how - you'd expect. - - @namespace - @method hasMany - @for DS - @param {String} type (optional) type of the relationship - @param {Object} options (optional) a hash of options - @return {Ember.computed} relationship -*/ -export default function hasMany(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } - - assert( - `The first argument to DS.hasMany must be a string representing a model type key, not an instance of ${inspect( - type - )}. E.g., to define a relation to the Comment model, use DS.hasMany('comment')`, - typeof type === 'string' || typeof type === 'undefined' - ); - - options = options || {}; - - if (typeof type === 'string') { - type = normalizeModelName(type); - } - - // Metadata about relationships is stored on the meta of - // the relationship. This is used for introspection and - // serialization. Note that `key` is populated lazily - // the first time the CP is called. - let meta = { - type, - options, - isRelationship: true, - kind: 'hasMany', - name: 'Has Many', - key: null, - }; - - return computed({ - get(key) { - return this._internalModel._relationships.get(key).getData(); - }, - set(key, records) { - this._internalModel.setDirtyHasMany(key, records); - - return this._internalModel._relationships.get(key).getData(); - }, - }).meta(meta); -} diff --git a/addon/-legacy-private/system/relationships/relationship-payloads-manager.js b/addon/-legacy-private/system/relationships/relationship-payloads-manager.js deleted file mode 100644 index 64282e729cf..00000000000 --- a/addon/-legacy-private/system/relationships/relationship-payloads-manager.js +++ /dev/null @@ -1,346 +0,0 @@ -import { get } from '@ember/object'; -// import { DEBUG } from '@glimmer/env'; -import { assert } from '@ember/debug'; -import { default as RelationshipPayloads, TypeCache } from './relationship-payloads'; - -/** - Manages relationship payloads for a given store, for uninitialized - relationships. Acts as a single source of truth (of payloads) for both sides - of an uninitialized relationship so they can agree on the most up-to-date - payload received without needing too much eager processing when those payloads - are pushed into the store. - - This minimizes the work spent on relationships that are never initialized. - - Once relationships are initialized, their state is managed in a relationship - state object (eg BelongsToRelationship or ManyRelationship). - - - @example - - let relationshipPayloadsManager = new RelationshipPayloadsManager(store); - - const User = DS.Model.extend({ - hobbies: DS.hasMany('hobby') - }); - - const Hobby = DS.Model.extend({ - user: DS.belongsTo('user') - }); - - let userPayload = { - data: { - id: 1, - type: 'user', - relationships: { - hobbies: { - data: [{ - id: 2, - type: 'hobby' - }] - } - } - }, - }; - relationshipPayloadsManager.push('user', 1, userPayload.data.relationships); - - relationshipPayloadsManager.get('hobby', 2, 'user') === { - { - data: { - id: 1, - type: 'user' - } - } - } - - @private - @class RelationshipPayloadsManager -*/ -export default class RelationshipPayloadsManager { - constructor(store) { - this._store = store; - // cache of `RelationshipPayload`s - this._cache = Object.create(null); - this._inverseLookupCache = new TypeCache(); - } - - /** - Find the payload for the given relationship of the given model. - - Returns the payload for the given relationship, whether raw or computed from - the payload of the inverse relationship. - - @example - - relationshipPayloadsManager.get('hobby', 2, 'user') === { - { - data: { - id: 1, - type: 'user' - } - } - } - - @method - */ - get(modelName, id, relationshipName) { - let relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false); - return relationshipPayloads && relationshipPayloads.get(modelName, id, relationshipName); - } - - /** - Push a model's relationships payload into this cache. - - @example - - let userPayload = { - data: { - id: 1, - type: 'user', - relationships: { - hobbies: { - data: [{ - id: 2, - type: 'hobby' - }] - } - } - }, - }; - relationshipPayloadsManager.push('user', 1, userPayload.data.relationships); - - @method - */ - push(modelName, id, relationshipsData) { - if (!relationshipsData) { - return; - } - - Object.keys(relationshipsData).forEach(key => { - let relationshipPayloads = this._getRelationshipPayloads(modelName, key, true); - if (relationshipPayloads) { - relationshipPayloads.push(modelName, id, key, relationshipsData[key]); - } - }); - } - - /** - Unload a model's relationships payload. - - @method - */ - unload(modelName, id) { - let modelClass = this._store.modelFor(modelName); - let relationshipsByName = get(modelClass, 'relationshipsByName'); - relationshipsByName.forEach((_, relationshipName) => { - let relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false); - if (relationshipPayloads) { - relationshipPayloads.unload(modelName, id, relationshipName); - } - }); - } - - /** - Find the RelationshipPayloads object for the given relationship. The same - RelationshipPayloads object is returned for either side of a relationship. - - @example - - const User = DS.Model.extend({ - hobbies: DS.hasMany('hobby') - }); - - const Hobby = DS.Model.extend({ - user: DS.belongsTo('user') - }); - - relationshipPayloads.get('user', 'hobbies') === relationshipPayloads.get('hobby', 'user'); - - The signature has a somewhat large arity to avoid extra work, such as - a) string manipulation & allocation with `modelName` and - `relationshipName` - b) repeatedly getting `relationshipsByName` via `Ember.get` - - - @private - @method - */ - _getRelationshipPayloads(modelName, relationshipName, init) { - let relInfo = this.getRelationshipInfo(modelName, relationshipName); - - if (relInfo === null) { - return; - } - - let cache = this._cache[relInfo.lhs_key]; - - if (!cache && init) { - return this._initializeRelationshipPayloads(relInfo); - } - - return cache; - } - - getRelationshipInfo(modelName, relationshipName) { - let inverseCache = this._inverseLookupCache; - let store = this._store; - let cached = inverseCache.get(modelName, relationshipName); - - // CASE: We have a cached resolution (null if no relationship exists) - if (cached !== undefined) { - return cached; - } - - let modelClass = store.modelFor(modelName); - let relationshipsByName = get(modelClass, 'relationshipsByName'); - - // CASE: We don't have a relationship at all - if (!relationshipsByName.has(relationshipName)) { - inverseCache.set(modelName, relationshipName, null); - return null; - } - - let relationshipMeta = relationshipsByName.get(relationshipName); - let inverseMeta; - - // CASE: Inverse is explicitly null - if (relationshipMeta.options && relationshipMeta.options.inverse === null) { - inverseMeta = null; - } else { - inverseMeta = modelClass.inverseFor(relationshipName, store); - } - - let selfIsPolymorphic = - relationshipMeta.options !== undefined && relationshipMeta.options.polymorphic === true; - let inverseBaseModelName = relationshipMeta.type; - - // CASE: We have no inverse - if (!inverseMeta) { - let info = { - lhs_key: `${modelName}:${relationshipName}`, - lhs_modelNames: [modelName], - lhs_baseModelName: modelName, - lhs_relationshipName: relationshipName, - lhs_relationshipMeta: relationshipMeta, - lhs_isPolymorphic: selfIsPolymorphic, - rhs_key: '', - rhs_modelNames: [], - rhs_baseModelName: inverseBaseModelName, - rhs_relationshipName: '', - rhs_relationshipMeta: null, - rhs_isPolymorphic: false, - hasInverse: false, - isSelfReferential: false, // modelName === inverseBaseModelName, - isReflexive: false, - }; - - inverseCache.set(modelName, relationshipName, info); - - return info; - } - - // CASE: We do have an inverse - - let inverseRelationshipName = inverseMeta.name; - let inverseRelationshipMeta = get(inverseMeta.type, 'relationshipsByName').get( - inverseRelationshipName - ); - let baseModelName = inverseRelationshipMeta.type; - let isSelfReferential = baseModelName === inverseBaseModelName; - - // TODO we want to assert this but this breaks all of our shoddily written tests - /* - if (DEBUG) { - let inverseDoubleCheck = inverseMeta.type.inverseFor(inverseRelationshipName, store); - - assert(`The ${inverseBaseModelName}:${inverseRelationshipName} relationship declares 'inverse: null', but it was resolved as the inverse for ${baseModelName}:${relationshipName}.`, inverseDoubleCheck); - } - */ - - // CASE: We may have already discovered the inverse for the baseModelName - // CASE: We have already discovered the inverse - cached = - inverseCache.get(baseModelName, relationshipName) || - inverseCache.get(inverseBaseModelName, inverseRelationshipName); - if (cached) { - // TODO this assert can be removed if the above assert is enabled - assert( - `The ${inverseBaseModelName}:${inverseRelationshipName} relationship declares 'inverse: null', but it was resolved as the inverse for ${baseModelName}:${relationshipName}.`, - cached.hasInverse !== false - ); - - let isLHS = cached.lhs_baseModelName === baseModelName; - let modelNames = isLHS ? cached.lhs_modelNames : cached.rhs_modelNames; - // make this lookup easier in the future by caching the key - modelNames.push(modelName); - inverseCache.set(modelName, relationshipName, cached); - - return cached; - } - - let info = { - lhs_key: `${baseModelName}:${relationshipName}`, - lhs_modelNames: [modelName], - lhs_baseModelName: baseModelName, - lhs_relationshipName: relationshipName, - lhs_relationshipMeta: relationshipMeta, - lhs_isPolymorphic: selfIsPolymorphic, - rhs_key: `${inverseBaseModelName}:${inverseRelationshipName}`, - rhs_modelNames: [], - rhs_baseModelName: inverseBaseModelName, - rhs_relationshipName: inverseRelationshipName, - rhs_relationshipMeta: inverseRelationshipMeta, - rhs_isPolymorphic: - inverseRelationshipMeta.options !== undefined && - inverseRelationshipMeta.options.polymorphic === true, - hasInverse: true, - isSelfReferential, - isReflexive: isSelfReferential && relationshipName === inverseRelationshipName, - }; - - // Create entries for the baseModelName as well as modelName to speed up - // inverse lookups - inverseCache.set(baseModelName, relationshipName, info); - inverseCache.set(modelName, relationshipName, info); - - // Greedily populate the inverse - inverseCache.set(inverseBaseModelName, inverseRelationshipName, info); - - return info; - } - - /** - Create the `RelationshipsPayload` for the relationship `modelName`, `relationshipName`, and its inverse. - - @private - @method - */ - _initializeRelationshipPayloads(relInfo) { - let lhsKey = relInfo.lhs_key; - let rhsKey = relInfo.rhs_key; - let existingPayloads = this._cache[lhsKey]; - - if (relInfo.hasInverse === true && relInfo.rhs_isPolymorphic === true) { - existingPayloads = this._cache[rhsKey]; - - if (existingPayloads !== undefined) { - this._cache[lhsKey] = existingPayloads; - return existingPayloads; - } - } - - // populate the cache for both sides of the relationship, as they both use - // the same `RelationshipPayloads`. - // - // This works out better than creating a single common key, because to - // compute that key we would need to do work to look up the inverse - // - let cache = (this._cache[lhsKey] = new RelationshipPayloads(relInfo)); - - if (relInfo.hasInverse === true) { - this._cache[rhsKey] = cache; - } - - return cache; - } -} diff --git a/addon/-legacy-private/system/relationships/relationship-payloads.js b/addon/-legacy-private/system/relationships/relationship-payloads.js deleted file mode 100644 index 478c345eee8..00000000000 --- a/addon/-legacy-private/system/relationships/relationship-payloads.js +++ /dev/null @@ -1,499 +0,0 @@ -import { assert } from '@ember/debug'; - -/** - * Merge data,meta,links information forward to the next payload - * if required. Latest data will always win. - * - * @param oldPayload - * @param newPayload - */ -function mergeForwardPayload(oldPayload, newPayload) { - if (oldPayload && oldPayload.data !== undefined && newPayload.data === undefined) { - newPayload.data = oldPayload.data; - } - - /* - _partialData is has-many relationship data that has been discovered via - inverses in the absence of canonical `data` availability from the primary - payload. - - We can't merge this data into `data` as that would trick has-many relationships - into believing they know their complete membership. Anytime we find canonical - data from the primary record, this partial data is discarded. If no canonical - data is ever discovered, the partial data will be loaded by the relationship - in a way that correctly preserves the `stale` relationship state. - */ - if (newPayload.data === undefined && oldPayload && oldPayload._partialData !== undefined) { - newPayload._partialData = oldPayload._partialData; - } - - if (oldPayload && oldPayload.meta !== undefined && newPayload.meta === undefined) { - newPayload.meta = oldPayload.meta; - } - - if (oldPayload && oldPayload.links !== undefined && newPayload.links === undefined) { - newPayload.links = oldPayload.links; - } -} - -// TODO this is now VERY similar to the identity/internal-model map -// so we should probably generalize -export class TypeCache { - constructor() { - this.types = Object.create(null); - } - get(modelName, id) { - let { types } = this; - - if (types[modelName] !== undefined) { - return types[modelName][id]; - } - } - - set(modelName, id, payload) { - let { types } = this; - let typeMap = types[modelName]; - - if (typeMap === undefined) { - typeMap = types[modelName] = Object.create(null); - } - - typeMap[id] = payload; - } - - delete(modelName, id) { - let { types } = this; - - if (types[modelName] !== undefined) { - delete types[modelName][id]; - } - } -} - -/** - Manages the payloads for both sides of a single relationship, across all model - instances. - - For example, with - - const User = DS.Model.extend({ - hobbies: DS.hasMany('hobby') - }); - - const Hobby = DS.Model.extend({ - user: DS.belongsTo('user') - }); - - let relationshipPayloads = new RelationshipPayloads('user', 'hobbies', 'hobby', 'user'); - - let userPayload = { - data: { - id: 1, - type: 'user', - relationships: { - hobbies: { - data: [{ - id: 2, - type: 'hobby', - }] - } - } - } - }; - - // here we expect the payload of the individual relationship - relationshipPayloads.push('user', 1, 'hobbies', userPayload.data.relationships.hobbies); - - relationshipPayloads.get('user', 1, 'hobbies'); - relationshipPayloads.get('hobby', 2, 'user'); - - @class RelationshipPayloads - @private - */ -export default class RelationshipPayloads { - constructor(relInfo) { - this._relInfo = relInfo; - - // a map of id -> payloads for the left hand side of the relationship. - this.lhs_payloads = new TypeCache(); - this.rhs_payloads = relInfo.isReflexive ? this.lhs_payloads : new TypeCache(); - - // When we push relationship payloads, just stash them in a queue until - // somebody actually asks for one of them. - // - // This is a queue of the relationship payloads that have been pushed for - // either side of this relationship - this._pendingPayloads = []; - } - - /** - Get the payload for the relationship of an individual record. - - This might return the raw payload as pushed into the store, or one computed - from the payload of the inverse relationship. - - @method - */ - get(modelName, id, relationshipName) { - this._flushPending(); - - if (this._isLHS(modelName, relationshipName)) { - return this.lhs_payloads.get(modelName, id); - } else { - assert( - `${modelName}:${relationshipName} is not either side of this relationship, ${ - this._relInfo.lhs_key - }<->${this._relInfo.rhs_key}`, - this._isRHS(modelName, relationshipName) - ); - return this.rhs_payloads.get(modelName, id); - } - } - - /** - Push a relationship payload for an individual record. - - This will make the payload available later for both this relationship and its inverse. - - @method - */ - push(modelName, id, relationshipName, relationshipData) { - this._pendingPayloads.push([modelName, id, relationshipName, relationshipData]); - } - - /** - Unload the relationship payload for an individual record. - - This does not unload the inverse relationship payload. - - @method - */ - unload(modelName, id, relationshipName) { - this._flushPending(); - - if (this._isLHS(modelName, relationshipName)) { - this.lhs_payloads.delete(modelName, id); - } else { - assert( - `${modelName}:${relationshipName} is not either side of this relationship, ${ - this._relInfo.lhs_baseModelName - }:${this._relInfo.lhs_relationshipName}<->${this._relInfo.rhs_baseModelName}:${ - this._relInfo.rhs_relationshipName - }`, - this._isRHS(modelName, relationshipName) - ); - this.rhs_payloads.delete(modelName, id); - } - } - - /** - @return {boolean} true iff `modelName` and `relationshipName` refer to the - left hand side of this relationship, as opposed to the right hand side. - - @method - */ - _isLHS(modelName, relationshipName) { - let relInfo = this._relInfo; - let isSelfReferential = relInfo.isSelfReferential; - let isRelationship = relationshipName === relInfo.lhs_relationshipName; - - if (isRelationship === true) { - return ( - isSelfReferential === true || // itself - modelName === relInfo.lhs_baseModelName || // base or non-polymorphic - relInfo.lhs_modelNames.indexOf(modelName) !== -1 - ); // polymorphic - } - - return false; - } - - /** - @return {boolean} true iff `modelName` and `relationshipName` refer to the - right hand side of this relationship, as opposed to the left hand side. - - @method - */ - _isRHS(modelName, relationshipName) { - let relInfo = this._relInfo; - let isSelfReferential = relInfo.isSelfReferential; - let isRelationship = relationshipName === relInfo.rhs_relationshipName; - - if (isRelationship === true) { - return ( - isSelfReferential === true || // itself - modelName === relInfo.rhs_baseModelName || // base or non-polymorphic - relInfo.rhs_modelNames.indexOf(modelName) !== -1 - ); // polymorphic - } - - return false; - } - - _flushPending() { - if (this._pendingPayloads.length === 0) { - return; - } - - let payloadsToBeProcessed = this._pendingPayloads.splice(0, this._pendingPayloads.length); - for (let i = 0; i < payloadsToBeProcessed.length; ++i) { - let modelName = payloadsToBeProcessed[i][0]; - let id = payloadsToBeProcessed[i][1]; - let relationshipName = payloadsToBeProcessed[i][2]; - let relationshipData = payloadsToBeProcessed[i][3]; - - // TODO: maybe delay this allocation slightly? - let inverseRelationshipData = { - data: { - id: id, - type: modelName, - }, - }; - - // start flushing this individual payload. The logic is the same whether - // it's for the left hand side of the relationship or the right hand side, - // except the role of primary and inverse idToPayloads is reversed - // - let previousPayload; - let payloadMap; - let inversePayloadMap; - let inverseIsMany; - if (this._isLHS(modelName, relationshipName)) { - previousPayload = this.lhs_payloads.get(modelName, id); - payloadMap = this.lhs_payloads; - inversePayloadMap = this.rhs_payloads; - inverseIsMany = this._rhsRelationshipIsMany; - } else { - assert( - `${modelName}:${relationshipName} is not either side of this relationship, ${ - this._relInfo.lhs_key - }<->${this._relInfo.rhs_key}`, - this._isRHS(modelName, relationshipName) - ); - previousPayload = this.rhs_payloads.get(modelName, id); - payloadMap = this.rhs_payloads; - inversePayloadMap = this.lhs_payloads; - inverseIsMany = this._lhsRelationshipIsMany; - } - - // actually flush this individual payload - // - // We remove the previous inverse before populating our current one - // because we may have multiple payloads for the same relationship, in - // which case the last one wins. - // - // eg if user hasMany helicopters, and helicopter belongsTo user and we see - // - // [{ - // data: { - // id: 1, - // type: 'helicopter', - // relationships: { - // user: { - // id: 2, - // type: 'user' - // } - // } - // } - // }, { - // data: { - // id: 1, - // type: 'helicopter', - // relationships: { - // user: { - // id: 4, - // type: 'user' - // } - // } - // } - // }] - // - // Then we will initially have set user:2 as having helicopter:1, which we - // need to remove before adding helicopter:1 to user:4 - // - // only remove relationship information before adding if there is relationshipData.data - // * null is considered new information "empty", and it should win - // * undefined is NOT considered new information, we should keep original state - // * anything else is considered new information, and it should win - let isMatchingIdentifier = this._isMatchingIdentifier( - relationshipData && relationshipData.data, - previousPayload && previousPayload.data - ); - - if (relationshipData.data !== undefined) { - if (!isMatchingIdentifier) { - this._removeInverse(id, previousPayload, inversePayloadMap); - } - } - - mergeForwardPayload(previousPayload, relationshipData); - payloadMap.set(modelName, id, relationshipData); - - if (!isMatchingIdentifier) { - this._populateInverse( - relationshipData, - inverseRelationshipData, - inversePayloadMap, - inverseIsMany - ); - } - } - } - - _isMatchingIdentifier(a, b) { - return a && b && a.type === b.type && a.id === b.id && !Array.isArray(a) && !Array.isArray(b); - } - - /** - Populate the inverse relationship for `relationshipData`. - - If `relationshipData` is an array (eg because the relationship is hasMany) - this means populate each inverse, otherwise populate only the single - inverse. - - @private - @method - */ - _populateInverse(relationshipData, inversePayload, inversePayloadMap, inverseIsMany) { - if (!relationshipData.data) { - // This id doesn't have an inverse, eg a belongsTo with a payload - // { data: null }, so there's nothing to populate - return; - } - - if (Array.isArray(relationshipData.data)) { - for (let i = 0; i < relationshipData.data.length; ++i) { - let resourceIdentifier = relationshipData.data[i]; - this._addToInverse(inversePayload, resourceIdentifier, inversePayloadMap, inverseIsMany); - } - } else { - let resourceIdentifier = relationshipData.data; - this._addToInverse(inversePayload, resourceIdentifier, inversePayloadMap, inverseIsMany); - } - } - - /** - Actually add `inversePayload` to `inverseIdToPayloads`. This is part of - `_populateInverse` after we've normalized the case of `relationshipData` - being either an array or a pojo. - - We still have to handle the case that the *inverse* relationship payload may - be an array or pojo. - - @private - @method - */ - _addToInverse(inversePayload, resourceIdentifier, inversePayloadMap, inverseIsMany) { - let relInfo = this._relInfo; - let inverseData = inversePayload.data; - - if (relInfo.isReflexive && inverseData && inverseData.id === resourceIdentifier.id) { - // eg .friends = [{ id: 1, type: 'user' }] - return; - } - - let existingPayload = inversePayloadMap.get(resourceIdentifier.type, resourceIdentifier.id); - - if (existingPayload) { - // There already is an inverse, either add or overwrite depending on - // whether the inverse is a many relationship or not - // - if (inverseIsMany) { - let existingData = existingPayload.data; - - // in the case of a hasMany - // we do not want create a `data` array where there was none before - // if we also have links, which this would indicate - if (existingData) { - existingData.push(inversePayload.data); - } else { - existingPayload._partialData = existingPayload._partialData || []; - existingPayload._partialData.push(inversePayload.data); - } - } else { - mergeForwardPayload(existingPayload, inversePayload); - inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, inversePayload); - } - } else { - // first time we're populating the inverse side - // - if (inverseIsMany) { - inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, { - _partialData: [inversePayload.data], - }); - } else { - inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, inversePayload); - } - } - } - - get _lhsRelationshipIsMany() { - let meta = this._relInfo.lhs_relationshipMeta; - return meta !== null && meta.kind === 'hasMany'; - } - - get _rhsRelationshipIsMany() { - let meta = this._relInfo.rhs_relationshipMeta; - return meta !== null && meta.kind === 'hasMany'; - } - - /** - Remove the relationship in `previousPayload` from its inverse(s), because - this relationship payload has just been updated (eg because the same - relationship had multiple payloads pushed before the relationship was - initialized). - - @method - */ - _removeInverse(id, previousPayload, inversePayloadMap) { - let data = previousPayload && previousPayload.data; - let partialData = previousPayload && previousPayload._partialData; - let maybeData = data || partialData; - - if (!maybeData) { - // either this is the first time we've seen a payload for this id, or its - // previous payload indicated that it had no inverse, eg a belongsTo - // relationship with payload { data: null } - // - // In either case there's nothing that needs to be removed from the - // inverse map of payloads - return; - } - - if (Array.isArray(maybeData)) { - // TODO: diff rather than removeall addall? - for (let i = 0; i < maybeData.length; ++i) { - const resourceIdentifier = maybeData[i]; - this._removeFromInverse(id, resourceIdentifier, inversePayloadMap); - } - } else { - this._removeFromInverse(id, data, inversePayloadMap); - } - } - - /** - Remove `id` from its inverse record with id `inverseId`. If the inverse - relationship is a belongsTo, this means just setting it to null, if the - inverse relationship is a hasMany, then remove that id from its array of ids. - - @method - */ - _removeFromInverse(id, resourceIdentifier, inversePayloads) { - let inversePayload = inversePayloads.get(resourceIdentifier.type, resourceIdentifier.id); - let data = inversePayload && inversePayload.data; - let partialData = inversePayload && inversePayload._partialData; - - if (!data && !partialData) { - return; - } - - if (Array.isArray(data)) { - inversePayload.data = data.filter(x => x.id !== id); - } else if (Array.isArray(partialData)) { - inversePayload._partialData = partialData.filter(x => x.id !== id); - } else { - // this merges forward links and meta - inversePayload.data = null; - } - } -} diff --git a/addon/-legacy-private/system/relationships/state/belongs-to.js b/addon/-legacy-private/system/relationships/state/belongs-to.js deleted file mode 100644 index 8c7d0001c79..00000000000 --- a/addon/-legacy-private/system/relationships/state/belongs-to.js +++ /dev/null @@ -1,324 +0,0 @@ -import { resolve } from 'rsvp'; -import { assert } from '@ember/debug'; -import { assertPolymorphicType } from 'ember-data/-debug'; -import { PromiseBelongsTo, PromiseObject } from '../../promise-proxies'; -import Relationship from './relationship'; - -export default class BelongsToRelationship extends Relationship { - constructor(store, internalModel, inverseKey, relationshipMeta) { - super(store, internalModel, inverseKey, relationshipMeta); - this.inverseInternalModel = null; - this.canonicalState = null; - this._promiseProxy = null; - } - - /** - * Flag indicating whether all inverse records are available - * - * true if the inverse exists and is loaded (not empty) - * true if there is no inverse - * false if the inverse exists and is not loaded (empty) - * - * @property - * @return {boolean} - */ - get allInverseRecordsAreLoaded() { - let internalModel = this.inverseInternalModel; - let isEmpty = internalModel !== null && internalModel.isEmpty(); - - return !isEmpty; - } - - setInternalModel(internalModel) { - if (internalModel) { - this.addInternalModel(internalModel); - } else if (this.inverseInternalModel) { - this.removeInternalModel(this.inverseInternalModel); - } - - this.setHasAnyRelationshipData(true); - this.setRelationshipIsStale(false); - this.setRelationshipIsEmpty(false); - } - - setCanonicalInternalModel(internalModel) { - if (internalModel) { - this.addCanonicalInternalModel(internalModel); - } else if (this.canonicalState) { - this.removeCanonicalInternalModel(this.canonicalState); - } - this.flushCanonicalLater(); - } - - setInitialCanonicalInternalModel(internalModel) { - if (!internalModel) { - return; - } - - // When we initialize a belongsTo relationship, we want to avoid work like - // notifying our internalModel that we've "changed" and excessive thrash on - // setting up inverse relationships - this.canonicalMembers.add(internalModel); - this.members.add(internalModel); - this.inverseInternalModel = this.canonicalState = internalModel; - this.setupInverseRelationship(internalModel); - } - - addCanonicalInternalModel(internalModel) { - if (this.canonicalMembers.has(internalModel)) { - return; - } - - if (this.canonicalState) { - this.removeCanonicalInternalModel(this.canonicalState); - } - - this.canonicalState = internalModel; - this.setHasAnyRelationshipData(true); - this.setRelationshipIsEmpty(false); - super.addCanonicalInternalModel(internalModel); - } - - inverseDidDematerialize() { - super.inverseDidDematerialize(this.inverseInternalModel); - this.notifyBelongsToChange(); - } - - removeCompletelyFromOwn(internalModel) { - super.removeCompletelyFromOwn(internalModel); - - if (this.canonicalState === internalModel) { - this.canonicalState = null; - } - - if (this.inverseInternalModel === internalModel) { - this.inverseInternalModel = null; - this.notifyBelongsToChange(); - } - } - - removeCompletelyFromInverse() { - super.removeCompletelyFromInverse(); - - this.inverseInternalModel = null; - } - - flushCanonical() { - //temporary fix to not remove newly created records if server returned null. - //TODO remove once we have proper diffing - if (this.inverseInternalModel && this.inverseInternalModel.isNew() && !this.canonicalState) { - return; - } - if (this.inverseInternalModel !== this.canonicalState) { - this.inverseInternalModel = this.canonicalState; - this._promiseProxy = null; - this.notifyBelongsToChange(); - } - - super.flushCanonical(); - } - - addInternalModel(internalModel) { - if (this.members.has(internalModel)) { - return; - } - - assertPolymorphicType(this.internalModel, this.relationshipMeta, internalModel, this.store); - - if (this.inverseInternalModel) { - this.removeInternalModel(this.inverseInternalModel); - } - - this.inverseInternalModel = internalModel; - super.addInternalModel(internalModel); - this.notifyBelongsToChange(); - } - - setRecordPromise(belongsToPromise) { - assert( - 'You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.', - belongsToPromise instanceof PromiseObject - ); - - let content = belongsToPromise.get('content'); - let promise = belongsToPromise.get('promise'); - - this.setInternalModel(content ? content._internalModel : content); - this._updateLoadingPromise(promise, content); - } - - removeInternalModelFromOwn(internalModel) { - if (!this.members.has(internalModel)) { - return; - } - this.inverseInternalModel = null; - this._promiseProxy = null; - super.removeInternalModelFromOwn(internalModel); - this.notifyBelongsToChange(); - } - - removeAllInternalModelsFromOwn() { - super.removeAllInternalModelsFromOwn(); - this.inverseInternalModel = null; - this._promiseProxy = null; - this.notifyBelongsToChange(); - } - - notifyBelongsToChange() { - if (this._promiseProxy !== null) { - let iM = this.inverseInternalModel; - - this._updateLoadingPromise(proxyRecord(iM), iM ? iM.getRecord() : null); - } - - this.internalModel.notifyBelongsToChange(this.key); - } - - removeCanonicalInternalModelFromOwn(internalModel) { - if (!this.canonicalMembers.has(internalModel)) { - return; - } - this.canonicalState = null; - this.setHasAnyRelationshipData(true); - this.setRelationshipIsEmpty(true); - super.removeCanonicalInternalModelFromOwn(internalModel); - } - - removeAllCanonicalInternalModelsFromOwn() { - super.removeAllCanonicalInternalModelsFromOwn(); - this.canonicalState = null; - } - - // called by `getData()` when a request is needed - // but no link is available - _fetchRecord(options) { - let { inverseInternalModel, shouldForceReload } = this; - - if (inverseInternalModel) { - let promise; - - if (shouldForceReload && !inverseInternalModel.isEmpty() && inverseInternalModel.hasRecord) { - // reload record, if it is already loaded - // if we have a link, we would already be in `findLink()` - promise = inverseInternalModel.getRecord().reload(options); - } else { - promise = this.store._findByInternalModel(inverseInternalModel, options); - } - - return promise; - } - - // TODO is this actually an error case? - return resolve(null); - } - - // called by `getData()` when a request is needed - // and a link is available - _fetchLink(options) { - return this.store - .findBelongsTo(this.internalModel, this.link, this.relationshipMeta, options) - .then(internalModel => { - if (internalModel) { - this.addInternalModel(internalModel); - } - return internalModel; - }); - } - - /* - While the `shouldForceReload` flag will also be true when `isForcedReload` is true, - `isForcedReload` is only `true` for an initial `getData` call during a forced reload. - Other calls must conform to the typical expectations, for instance, sync relationships - expect that their data is already loaded. - */ - getData(options, isForcedReload = false) { - //TODO(Igor) flushCanonical here once our syncing is not stupid - let record = this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null; - - if (this.shouldMakeRequest()) { - let promise; - - if (this.link) { - promise = this._fetchLink(options); - } else { - promise = this._fetchRecord(options); - } - - promise = promise.then(() => handleCompletedFind(this), e => handleCompletedFind(this, e)); - - promise = promise.then(internalModel => { - return internalModel ? internalModel.getRecord() : null; - }); - - this.fetchPromise = promise; - this._updateLoadingPromise(promise); - } - - if (this.isAsync) { - if (this._promiseProxy === null) { - let promise = proxyRecord(this.inverseInternalModel); - this._updateLoadingPromise(promise, record); - } - - return this._promiseProxy; - } else { - assert( - "You looked up the '" + - this.key + - "' relationship on a '" + - this.internalModel.modelName + - "' with id " + - this.internalModel.id + - ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)', - record === null || !record.get('isEmpty') || isForcedReload - ); - return record; - } - } - - _createProxy(promise, content) { - return PromiseBelongsTo.create({ - _belongsToState: this, - promise, - content, - }); - } - - updateData(data, initial) { - let internalModel = this.store._pushResourceIdentifier(this, data); - if (initial) { - this.setInitialCanonicalInternalModel(internalModel); - } else { - this.setCanonicalInternalModel(internalModel); - } - } -} - -function proxyRecord(internalModel) { - let promise = internalModel; - if (internalModel && internalModel.isLoading()) { - promise = internalModel._promiseProxy; - } - - return resolve(promise).then(resolvedInternalModel => { - return resolvedInternalModel ? resolvedInternalModel.getRecord() : null; - }); -} - -function handleCompletedFind(relationship, error) { - let internalModel = relationship.inverseInternalModel; - - relationship.fetchPromise = null; - relationship.setShouldForceReload(false); - - if (error) { - relationship.setHasFailedLoadAttempt(true); - throw error; - } - - relationship.setHasFailedLoadAttempt(false); - // only set to not stale if no error is thrown - relationship.setRelationshipIsStale(false); - - return internalModel; -} diff --git a/addon/-legacy-private/system/relationships/state/create.js b/addon/-legacy-private/system/relationships/state/create.js deleted file mode 100644 index ed82b773f7c..00000000000 --- a/addon/-legacy-private/system/relationships/state/create.js +++ /dev/null @@ -1,86 +0,0 @@ -import { get } from '@ember/object'; -import ManyRelationship from './has-many'; -import BelongsToRelationship from './belongs-to'; -import { DEBUG } from '@glimmer/env'; - -function shouldFindInverse(relationshipMeta) { - let options = relationshipMeta.options; - return !(options && options.inverse === null); -} - -function createRelationshipFor(internalModel, relationshipMeta, store) { - let inverseKey; - let inverse = null; - - if (shouldFindInverse(relationshipMeta)) { - inverse = internalModel.type.inverseFor(relationshipMeta.key, store); - } else if (DEBUG) { - internalModel.type.typeForRelationship(relationshipMeta.key, store); - } - - if (inverse) { - inverseKey = inverse.name; - } - - if (relationshipMeta.kind === 'hasMany') { - return new ManyRelationship(store, internalModel, inverseKey, relationshipMeta); - } else { - return new BelongsToRelationship(store, internalModel, inverseKey, relationshipMeta); - } -} - -export default class Relationships { - constructor(internalModel) { - this.internalModel = internalModel; - this.initializedRelationships = Object.create(null); - } - - // TODO @runspired deprecate this as it was never truly a record instance - get record() { - return this.internalModel; - } - - has(key) { - return !!this.initializedRelationships[key]; - } - - forEach(cb) { - let rels = this.initializedRelationships; - Object.keys(rels).forEach(name => { - cb(name, rels[name]); - }); - } - - get(key) { - let relationships = this.initializedRelationships; - let relationship = relationships[key]; - let internalModel = this.internalModel; - - if (!relationship) { - let relationshipsByName = get(internalModel.type, 'relationshipsByName'); - let rel = relationshipsByName.get(key); - - if (!rel) { - return undefined; - } - - let relationshipPayload = internalModel.store._relationshipsPayloads.get( - internalModel.modelName, - internalModel.id, - key - ); - - relationship = relationships[key] = createRelationshipFor( - internalModel, - rel, - internalModel.store - ); - - if (relationshipPayload) { - relationship.push(relationshipPayload, true); - } - } - - return relationship; - } -} diff --git a/addon/-legacy-private/system/relationships/state/has-many.js b/addon/-legacy-private/system/relationships/state/has-many.js deleted file mode 100755 index 19a581f7020..00000000000 --- a/addon/-legacy-private/system/relationships/state/has-many.js +++ /dev/null @@ -1,454 +0,0 @@ -import { assert } from '@ember/debug'; -import { assertPolymorphicType } from 'ember-data/-debug'; -import { PromiseManyArray } from '../../promise-proxies'; -import Relationship from './relationship'; -import OrderedSet from '../../ordered-set'; -import ManyArray from '../../many-array'; -import { resolve } from 'rsvp'; - -export default class ManyRelationship extends Relationship { - constructor(store, internalModel, inverseKey, relationshipMeta) { - super(store, internalModel, inverseKey, relationshipMeta); - this.belongsToType = relationshipMeta.type; - this.canonicalState = []; - // The ManyArray for this relationship - this._manyArray = null; - // The previous ManyArray for this relationship. It will be destroyed when - // we create a new many array, but in the interim it will be updated if - // inverse internal models are unloaded. - this._retainedManyArray = null; - this._promiseProxy = null; - this._willUpdateManyArray = false; - this._pendingManyArrayUpdates = null; - } - - get currentState() { - return this.members.list; - } - - /** - * Flag indicating whether all inverse records are available - * - * true if inverse records exist and are all loaded (all not empty) - * true if there are no inverse records - * false if the inverse records exist and any are not loaded (any empty) - * - * @property - * @return {boolean} - */ - get allInverseRecordsAreLoaded() { - // check currentState for unloaded records - let hasEmptyRecords = this.currentState.reduce((hasEmptyModel, i) => { - return hasEmptyModel || i.isEmpty(); - }, false); - - // check un-synced state for unloaded records - if (!hasEmptyRecords && this.willSync) { - hasEmptyRecords = this.canonicalState.reduce((hasEmptyModel, i) => { - return hasEmptyModel || !i.isEmpty(); - }, false); - } - - return !hasEmptyRecords; - } - - _createProxy(promise, content) { - return PromiseManyArray.create({ - promise, - content, - }); - } - - get manyArray() { - assert( - `Error: relationship ${this.parentType}:${ - this.key - } has both many array and retained many array`, - this._manyArray === null || this._retainedManyArray === null - ); - - if (!this._manyArray && !this.isDestroying) { - let isLoaded = this.hasFailedLoadAttempt || this.isNew || this.allInverseRecordsAreLoaded; - - this._manyArray = ManyArray.create({ - canonicalState: this.canonicalState, - store: this.store, - relationship: this, - type: this.store.modelFor(this.belongsToType), - record: this.internalModel, - meta: this.meta, - isPolymorphic: this.isPolymorphic, - isLoaded, - }); - - if (this._retainedManyArray !== null) { - this._retainedManyArray.destroy(); - this._retainedManyArray = null; - } - } - - return this._manyArray; - } - - removeInverseRelationships() { - super.removeInverseRelationships(); - if (this._manyArray) { - this._manyArray.destroy(); - this._manyArray = null; - } - - if (this._promiseProxy) { - this._promiseProxy.destroy(); - } - } - - updateMeta(meta) { - super.updateMeta(meta); - if (this._manyArray) { - this._manyArray.set('meta', meta); - } - } - - addCanonicalInternalModel(internalModel, idx) { - if (this.canonicalMembers.has(internalModel)) { - return; - } - if (idx !== undefined) { - this.canonicalState.splice(idx, 0, internalModel); - } else { - this.canonicalState.push(internalModel); - } - super.addCanonicalInternalModel(internalModel, idx); - } - - inverseDidDematerialize(inverseInternalModel) { - super.inverseDidDematerialize(inverseInternalModel); - if (this.isAsync) { - if (this._manyArray) { - this._retainedManyArray = this._manyArray; - this._manyArray = null; - } - this._removeInternalModelFromManyArray(this._retainedManyArray, inverseInternalModel); - } - this.notifyHasManyChange(); - } - - addInternalModel(internalModel, idx) { - if (this.members.has(internalModel)) { - return; - } - - assertPolymorphicType(this.internalModel, this.relationshipMeta, internalModel, this.store); - super.addInternalModel(internalModel, idx); - this.scheduleManyArrayUpdate(internalModel, idx); - } - - scheduleManyArrayUpdate(internalModel, idx) { - if (!this._manyArray) { - return; - } - - let pending = (this._pendingManyArrayUpdates = this._pendingManyArrayUpdates || []); - pending.push(internalModel, idx); - - if (this._willUpdateManyArray === true) { - return; - } - - this._willUpdateManyArray = true; - let backburner = this.store._backburner; - - backburner.join(() => { - backburner.schedule('syncRelationships', this, this._flushPendingManyArrayUpdates); - }); - } - - _flushPendingManyArrayUpdates() { - if (this._willUpdateManyArray === false) { - return; - } - - let pending = this._pendingManyArrayUpdates; - this._pendingManyArrayUpdates = []; - this._willUpdateManyArray = false; - - for (let i = 0; i < pending.length; i += 2) { - let internalModel = pending[i]; - let idx = pending[i + 1]; - - this.manyArray._addInternalModels([internalModel], idx); - } - } - - removeCanonicalInternalModelFromOwn(internalModel, idx) { - let i = idx; - if (!this.canonicalMembers.has(internalModel)) { - return; - } - if (i === undefined) { - i = this.canonicalState.indexOf(internalModel); - } - if (i > -1) { - this.canonicalState.splice(i, 1); - } - super.removeCanonicalInternalModelFromOwn(internalModel, idx); - } - - removeAllCanonicalInternalModelsFromOwn() { - this.canonicalMembers.clear(); - this.canonicalState.splice(0, this.canonicalState.length); - super.removeAllCanonicalInternalModelsFromOwn(); - } - - removeCompletelyFromOwn(internalModel) { - super.removeCompletelyFromOwn(internalModel); - - const canonicalIndex = this.canonicalState.indexOf(internalModel); - - if (canonicalIndex !== -1) { - this.canonicalState.splice(canonicalIndex, 1); - } - - const manyArray = this._manyArray; - - if (manyArray) { - const idx = manyArray.currentState.indexOf(internalModel); - - if (idx !== -1) { - manyArray.internalReplace(idx, 1); - } - } - } - - flushCanonical() { - super.flushCanonical(); - if (this._manyArray) { - this._manyArray.flushCanonical(); - } - } - - removeInternalModelFromOwn(internalModel, idx) { - if (!this.members.has(internalModel)) { - return; - } - super.removeInternalModelFromOwn(internalModel, idx); - // note that ensuring the many array is created, via `this.manyArray` - // (instead of `this._manyArray`) is intentional. - // - // Because we're removing from local, and not canonical, state, it is - // important that the many array is initialized now with those changes, - // otherwise it will be initialized with canonical state and we'll have - // lost the fact that this internalModel was removed. - this._removeInternalModelFromManyArray(this.manyArray, internalModel, idx); - this._removeInternalModelFromManyArray(this._retainedManyArray, internalModel, idx); - } - - removeAllInternalModelsFromOwn() { - super.removeAllInternalModelsFromOwn(); - // as with removeInternalModelFromOwn, we make sure the many array is - // instantiated, or we'll lose local removals, as we're not updating - // canonical state here. - this.manyArray.clear(); - if (this._retainedManyArray) { - this._retainedManyArray.clear(); - } - } - - _removeInternalModelFromManyArray(manyArray, internalModel, idx) { - if (manyArray === null) { - return; - } - - if (idx !== undefined) { - //TODO(Igor) not used currently, fix - manyArray.currentState.removeAt(idx); - } else { - manyArray._removeInternalModels([internalModel]); - } - } - - notifyRecordRelationshipAdded(internalModel, idx) { - this.internalModel.notifyHasManyAdded(this.key, internalModel, idx); - } - - computeChanges(internalModels = []) { - let members = this.canonicalMembers; - let internalModelsToRemove = []; - let internalModelSet = setForArray(internalModels); - - members.forEach(member => { - if (internalModelSet.has(member)) { - return; - } - - internalModelsToRemove.push(member); - }); - - this.removeCanonicalInternalModels(internalModelsToRemove); - - for (let i = 0, l = internalModels.length; i < l; i++) { - let internalModel = internalModels[i]; - this.removeCanonicalInternalModel(internalModel); - this.addCanonicalInternalModel(internalModel, i); - } - } - - setInitialInternalModels(internalModels) { - if (Array.isArray(internalModels) === false || internalModels.length === 0) { - return; - } - - for (let i = 0; i < internalModels.length; i++) { - let internalModel = internalModels[i]; - if (this.canonicalMembers.has(internalModel)) { - continue; - } - - this.canonicalMembers.add(internalModel); - this.members.add(internalModel); - this.setupInverseRelationship(internalModel); - } - - this.canonicalState = this.canonicalMembers.toArray(); - } - - // called by `getData()` when a request is needed - // but no link is available - _fetchRecords(options) { - let internalModels = this.currentState; - let { shouldForceReload } = this; - let promise; - - if (shouldForceReload === true) { - promise = this.store._scheduleFetchMany(internalModels, options); - } else { - promise = this.store.findMany(internalModels, options); - } - - return promise; - } - - // called by `getData()` when a request is needed - // and a link is available - _fetchLink(options) { - return this.store - .findHasMany(this.internalModel, this.link, this.relationshipMeta, options) - .then(records => { - if (records.hasOwnProperty('meta')) { - this.updateMeta(records.meta); - } - this.store._backburner.join(() => { - this.updateInternalModelsFromAdapter(records); - }); - return records; - }); - } - - getData(options, isForcedReload = false) { - //TODO(Igor) sync server here, once our syncing is not stupid - let manyArray = this.manyArray; - - if (this.shouldMakeRequest()) { - let promise; - - if (this.link) { - promise = this._fetchLink(options); - } else { - promise = this._fetchRecords(options); - } - - promise = promise.then( - () => handleCompletedRequest(this), - e => handleCompletedRequest(this, e) - ); - - this.fetchPromise = promise; - this._updateLoadingPromise(promise, manyArray); - } - - if (this.isAsync) { - if (this._promiseProxy === null) { - this._updateLoadingPromise(resolve(manyArray), manyArray); - } - - return this._promiseProxy; - } else { - assert( - `You looked up the '${this.key}' relationship on a '${ - this.internalModel.type.modelName - }' with id ${ - this.internalModel.id - } but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\`DS.hasMany({ async: true })\`)`, - this.allInverseRecordsAreLoaded || isForcedReload - ); - - return manyArray; - } - } - - notifyHasManyChange() { - this.internalModel.notifyHasManyAdded(this.key); - } - - updateData(data, initial) { - let internalModels = this.store._pushResourceIdentifiers(this, data); - if (initial) { - this.setInitialInternalModels(internalModels); - } else { - this.updateInternalModelsFromAdapter(internalModels); - } - } - - destroy() { - this.isDestroying = true; - super.destroy(); - let manyArray = this._manyArray; - if (manyArray) { - manyArray.destroy(); - this._manyArray = null; - } - - let proxy = this._promiseProxy; - - if (proxy) { - proxy.destroy(); - this._promiseProxy = null; - } - this.isDestroyed = true; - } -} - -function handleCompletedRequest(relationship, error) { - let manyArray = relationship.manyArray; - - //Goes away after the manyArray refactor - if (!manyArray.get('isDestroyed')) { - relationship.manyArray.set('isLoaded', true); - } - - relationship.fetchPromise = null; - relationship.setShouldForceReload(false); - - if (error) { - relationship.setHasFailedLoadAttempt(true); - throw error; - } - - relationship.setHasFailedLoadAttempt(false); - // only set to not stale if no error is thrown - relationship.setRelationshipIsStale(false); - - return manyArray; -} - -function setForArray(array) { - var set = new OrderedSet(); - - if (array) { - for (var i = 0, l = array.length; i < l; i++) { - set.add(array[i]); - } - } - - return set; -} diff --git a/addon/-legacy-private/system/relationships/state/relationship.js b/addon/-legacy-private/system/relationships/state/relationship.js deleted file mode 100644 index 5752b0fb0f7..00000000000 --- a/addon/-legacy-private/system/relationships/state/relationship.js +++ /dev/null @@ -1,747 +0,0 @@ -/* global heimdall */ -import { guidFor } from '@ember/object/internals'; -import { get } from '@ember/object'; - -import { assert, warn } from '@ember/debug'; -import OrderedSet from '../../ordered-set'; -import _normalizeLink from '../../normalize-link'; - -const { - addCanonicalInternalModel, - addCanonicalInternalModels, - addInternalModel, - addInternalModels, - clear, - flushCanonical, - flushCanonicalLater, - newRelationship, - push, - removeCanonicalInternalModel, - removeCanonicalInternalModelFromInverse, - removeCanonicalInternalModelFromOwn, - removeCanonicalInternalModels, - removeInternalModel, - removeInternalModelFromInverse, - removeInternalModelFromOwn, - removeInternalModels, - updateLink, - updateMeta, - updateInternalModelsFromAdapter, -} = heimdall.registerMonitor( - 'system.relationships.state.relationship', - 'addCanonicalInternalModel', - 'addCanonicalInternalModels', - 'addInternalModel', - 'addInternalModels', - 'clear', - 'flushCanonical', - 'flushCanonicalLater', - 'newRelationship', - 'push', - 'removeCanonicalInternalModel', - 'removeCanonicalInternalModelFromInverse', - 'removeCanonicalInternalModelFromOwn', - 'removeCanonicalInternalModels', - 'removeInternalModel', - 'removeInternalModelFromInverse', - 'removeInternalModelFromOwn', - 'removeInternalModels', - 'updateLink', - 'updateMeta', - 'updateInternalModelsFromAdapter' -); - -export default class Relationship { - constructor(store, internalModel, inverseKey, relationshipMeta) { - heimdall.increment(newRelationship); - let async = relationshipMeta.options.async; - let polymorphic = relationshipMeta.options.polymorphic; - this.members = new OrderedSet(); - this.canonicalMembers = new OrderedSet(); - this.store = store; - this.key = relationshipMeta.key; - this.kind = relationshipMeta.kind; - this.inverseKey = inverseKey; - this.internalModel = internalModel; - this.isAsync = typeof async === 'undefined' ? true : async; - this.isPolymorphic = typeof polymorphic === 'undefined' ? false : polymorphic; - this.relationshipMeta = relationshipMeta; - //This probably breaks for polymorphic relationship in complex scenarios, due to - //multiple possible modelNames - this.inverseKeyForImplicit = this.internalModel.modelName + this.key; - this.fetchPromise = null; - this._promiseProxy = null; - this.meta = null; - this.__inverseMeta = undefined; - - /* - This flag forces fetch. `true` for a single request once `reload()` - has been called `false` at all other times. - */ - this.shouldForceReload = false; - - /* - This flag indicates whether we should - re-fetch the relationship the next time - it is accessed. - - The difference between this flag and `shouldForceReload` - is in how we treat the presence of partially missing data: - - for a forced reload, we will reload the link or EVERY record - - for a stale reload, we will reload the link (if present) else only MISSING records - - Ideally these flags could be merged, but because we don't give the - request layer the option of deciding how to resolve the data being queried - we are forced to differentiate for now. - - It is also possible for a relationship to remain stale after a forced reload; however, - in this case `hasFailedLoadAttempt` ought to be `true`. - - false when - => internalModel.isNew() on initial setup - => a previously triggered request has resolved - => we get relationship data via push - - true when - => !internalModel.isNew() on initial setup - => an inverse has been unloaded - => we get a new link for the relationship - */ - this.relationshipIsStale = !this.isNew; - - /* - This flag indicates whether we should consider the content - of this relationship "known". - - If we have no relationship knowledge, and the relationship - is `async`, we will attempt to fetch the relationship on - access if it is also stale. - - Snapshot uses this to tell the difference between unknown - (`undefined`) or empty (`null`). The reason for this is that - we wouldn't want to serialize unknown relationships as `null` - as that might overwrite remote state. - - All relationships for a newly created (`store.createRecord()`) are - considered known (`hasAnyRelationshipData === true`). - - true when - => we receive a push with either new data or explicit empty (`[]` or `null`) - => the relationship is a belongsTo and we have received data from - the other side. - - false when - => we have received no signal about what data belongs in this relationship - => the relationship is a hasMany and we have only received data from - the other side. - */ - this.hasAnyRelationshipData = false; - - /* - Flag that indicates whether an empty relationship is explicitly empty - (signaled by push giving us an empty array or null relationship) - e.g. an API response has told us that this relationship is empty. - - Thus far, it does not appear that we actually need this flag; however, - @runspired has found it invaluable when debugging relationship tests - to determine whether (and why if so) we are in an incorrect state. - - true when - => we receive a push with explicit empty (`[]` or `null`) - => we have received no signal about what data belongs in this relationship - => on initial create (as no signal is known yet) - - false at all other times - */ - this.relationshipIsEmpty = true; - - /* - Flag that indicates whether we have explicitly attempted a load for the relationship - (which may have failed) - */ - this.hasFailedLoadAttempt = false; - - /* - true when - => hasAnyRelationshipData is true - AND - => members (NOT canonicalMembers) @each !isEmpty - - TODO, consider changing the conditional here from !isEmpty to !hiddenFromRecordArrays - */ - } - - get isNew() { - return this.internalModel.isNew(); - } - - _inverseIsSync() { - let inverseMeta = this._inverseMeta; - if (!inverseMeta) { - return false; - } - - let inverseAsync = inverseMeta.options.async; - return typeof inverseAsync === 'undefined' ? false : !inverseAsync; - } - - get _inverseMeta() { - if (this.__inverseMeta === undefined) { - let inverseMeta = null; - - if (this.inverseKey) { - let inverseModelClass = this.store.modelFor(this.relationshipMeta.type); - let inverseRelationships = get(inverseModelClass, 'relationshipsByName'); - inverseMeta = inverseRelationships.get(this.inverseKey); - } - - this.__inverseMeta = inverseMeta; - } - - return this.__inverseMeta; - } - - get parentType() { - return this.internalModel.modelName; - } - - internalModelDidDematerialize() { - if (!this.inverseKey) { - return; - } - - this.forAllMembers(inverseInternalModel => { - let relationship = inverseInternalModel._relationships.get(this.inverseKey); - relationship.inverseDidDematerialize(this.internalModel); - }); - } - - inverseDidDematerialize(inverseInternalModel) { - this.fetchPromise = null; - this.setRelationshipIsStale(true); - - if (!this.isAsync) { - // unloading inverse of a sync relationship is treated as a client-side - // delete, so actually remove the models don't merely invalidate the cp - // cache. - this.removeInternalModelFromOwn(inverseInternalModel); - this.removeCanonicalInternalModelFromOwn(inverseInternalModel); - } - } - - updateMeta(meta) { - heimdall.increment(updateMeta); - this.meta = meta; - } - - clear() { - heimdall.increment(clear); - - let members = this.members.list; - while (members.length > 0) { - let member = members[0]; - this.removeInternalModel(member); - } - - let canonicalMembers = this.canonicalMembers.list; - while (canonicalMembers.length > 0) { - let member = canonicalMembers[0]; - this.removeCanonicalInternalModel(member); - } - } - - removeAllInternalModelsFromOwn() { - this.members.clear(); - this.internalModel.updateRecordArrays(); - } - - removeAllCanonicalInternalModelsFromOwn() { - this.canonicalMembers.clear(); - this.flushCanonicalLater(); - } - - removeInternalModels(internalModels) { - heimdall.increment(removeInternalModels); - internalModels.forEach(internalModel => this.removeInternalModel(internalModel)); - } - - addInternalModels(internalModels, idx) { - heimdall.increment(addInternalModels); - internalModels.forEach(internalModel => { - this.addInternalModel(internalModel, idx); - if (idx !== undefined) { - idx++; - } - }); - } - - addCanonicalInternalModels(internalModels, idx) { - heimdall.increment(addCanonicalInternalModels); - for (let i = 0; i < internalModels.length; i++) { - if (idx !== undefined) { - this.addCanonicalInternalModel(internalModels[i], i + idx); - } else { - this.addCanonicalInternalModel(internalModels[i]); - } - } - } - - addCanonicalInternalModel(internalModel, idx) { - heimdall.increment(addCanonicalInternalModel); - if (!this.canonicalMembers.has(internalModel)) { - this.canonicalMembers.addWithIndex(internalModel, idx); - this.setupInverseRelationship(internalModel); - } - this.flushCanonicalLater(); - this.setHasAnyRelationshipData(true); - } - - setupInverseRelationship(internalModel) { - if (this.inverseKey) { - let relationships = internalModel._relationships; - let relationshipExisted = relationships.has(this.inverseKey); - let relationship = relationships.get(this.inverseKey); - if (relationshipExisted || this.isPolymorphic) { - // if we have only just initialized the inverse relationship, then it - // already has this.internalModel in its canonicalMembers, so skip the - // unnecessary work. The exception to this is polymorphic - // relationships whose members are determined by their inverse, as those - // relationships cannot efficiently find their inverse payloads. - relationship.addCanonicalInternalModel(this.internalModel); - } - } else { - let relationships = internalModel._implicitRelationships; - let relationship = relationships[this.inverseKeyForImplicit]; - if (!relationship) { - relationship = relationships[this.inverseKeyForImplicit] = new Relationship( - this.store, - internalModel, - this.key, - { options: { async: this.isAsync }, type: this.parentType } - ); - } - relationship.addCanonicalInternalModel(this.internalModel); - } - } - - removeCanonicalInternalModels(internalModels, idx) { - heimdall.increment(removeCanonicalInternalModels); - for (let i = 0; i < internalModels.length; i++) { - if (idx !== undefined) { - this.removeCanonicalInternalModel(internalModels[i], i + idx); - } else { - this.removeCanonicalInternalModel(internalModels[i]); - } - } - } - - removeCanonicalInternalModel(internalModel, idx) { - heimdall.increment(removeCanonicalInternalModel); - if (this.canonicalMembers.has(internalModel)) { - this.removeCanonicalInternalModelFromOwn(internalModel); - if (this.inverseKey) { - this.removeCanonicalInternalModelFromInverse(internalModel); - } else { - if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) { - internalModel._implicitRelationships[ - this.inverseKeyForImplicit - ].removeCanonicalInternalModel(this.internalModel); - } - } - } - this.flushCanonicalLater(); - } - - addInternalModel(internalModel, idx) { - heimdall.increment(addInternalModel); - if (!this.members.has(internalModel)) { - this.members.addWithIndex(internalModel, idx); - this.notifyRecordRelationshipAdded(internalModel, idx); - if (this.inverseKey) { - internalModel._relationships.get(this.inverseKey).addInternalModel(this.internalModel); - } else { - if (!internalModel._implicitRelationships[this.inverseKeyForImplicit]) { - internalModel._implicitRelationships[this.inverseKeyForImplicit] = new Relationship( - this.store, - internalModel, - this.key, - { options: { async: this.isAsync }, type: this.parentType } - ); - } - internalModel._implicitRelationships[this.inverseKeyForImplicit].addInternalModel( - this.internalModel - ); - } - this.internalModel.updateRecordArrays(); - } - this.setHasAnyRelationshipData(true); - } - - removeInternalModel(internalModel) { - heimdall.increment(removeInternalModel); - if (this.members.has(internalModel)) { - this.removeInternalModelFromOwn(internalModel); - if (this.inverseKey) { - this.removeInternalModelFromInverse(internalModel); - } else { - if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) { - internalModel._implicitRelationships[this.inverseKeyForImplicit].removeInternalModel( - this.internalModel - ); - } - } - } - } - - removeInternalModelFromInverse(internalModel) { - heimdall.increment(removeInternalModelFromInverse); - let inverseRelationship = internalModel._relationships.get(this.inverseKey); - //Need to check for existence, as the record might unloading at the moment - if (inverseRelationship) { - inverseRelationship.removeInternalModelFromOwn(this.internalModel); - } - } - - removeInternalModelFromOwn(internalModel) { - heimdall.increment(removeInternalModelFromOwn); - this.members.delete(internalModel); - this.internalModel.updateRecordArrays(); - } - - removeCanonicalInternalModelFromInverse(internalModel) { - heimdall.increment(removeCanonicalInternalModelFromInverse); - let inverseRelationship = internalModel._relationships.get(this.inverseKey); - //Need to check for existence, as the record might unloading at the moment - if (inverseRelationship) { - inverseRelationship.removeCanonicalInternalModelFromOwn(this.internalModel); - } - } - - removeCanonicalInternalModelFromOwn(internalModel) { - heimdall.increment(removeCanonicalInternalModelFromOwn); - this.canonicalMembers.delete(internalModel); - this.flushCanonicalLater(); - } - - /* - Call this method once a record deletion has been persisted - to purge it from BOTH current and canonical state of all - relationships. - - @method removeCompletelyFromInverse - @private - */ - removeCompletelyFromInverse() { - if (!this.inverseKey) { - return; - } - - // we actually want a union of members and canonicalMembers - // they should be disjoint but currently are not due to a bug - let seen = Object.create(null); - const internalModel = this.internalModel; - - const unload = inverseInternalModel => { - const id = guidFor(inverseInternalModel); - - if (seen[id] === undefined) { - const relationship = inverseInternalModel._relationships.get(this.inverseKey); - relationship.removeCompletelyFromOwn(internalModel); - seen[id] = true; - } - }; - - this.members.forEach(unload); - this.canonicalMembers.forEach(unload); - - if (!this.isAsync) { - this.clear(); - } - } - - forAllMembers(callback) { - let seen = Object.create(null); - - for (let i = 0; i < this.members.list.length; i++) { - const inverseInternalModel = this.members.list[i]; - const id = guidFor(inverseInternalModel); - if (!seen[id]) { - seen[id] = true; - callback(inverseInternalModel); - } - } - - for (let i = 0; i < this.canonicalMembers.list.length; i++) { - const inverseInternalModel = this.canonicalMembers.list[i]; - const id = guidFor(inverseInternalModel); - if (!seen[id]) { - seen[id] = true; - callback(inverseInternalModel); - } - } - } - - /* - Removes the given internalModel from BOTH canonical AND current state. - - This method is useful when either a deletion or a rollback on a new record - needs to entirely purge itself from an inverse relationship. - */ - removeCompletelyFromOwn(internalModel) { - this.canonicalMembers.delete(internalModel); - this.members.delete(internalModel); - this.internalModel.updateRecordArrays(); - } - - flushCanonical() { - heimdall.increment(flushCanonical); - let list = this.members.list; - this.willSync = false; - //a hack for not removing new internalModels - //TODO remove once we have proper diffing - let newInternalModels = []; - for (let i = 0; i < list.length; i++) { - if (list[i].isNew()) { - newInternalModels.push(list[i]); - } - } - - //TODO(Igor) make this less abysmally slow - this.members = this.canonicalMembers.copy(); - for (let i = 0; i < newInternalModels.length; i++) { - this.members.add(newInternalModels[i]); - } - } - - flushCanonicalLater() { - heimdall.increment(flushCanonicalLater); - if (this.willSync) { - return; - } - this.willSync = true; - this.store._updateRelationshipState(this); - } - - updateLink(link) { - heimdall.increment(updateLink); - warn( - `You pushed a record of type '${this.internalModel.modelName}' with a relationship '${ - this.key - }' configured as 'async: false'. You've included a link but no primary data, this may be an error in your payload. EmberData will treat this relationship as known-to-be-empty.`, - this.isAsync || this.hasAnyRelationshipData, - { - id: 'ds.store.push-link-for-sync-relationship', - } - ); - assert( - `You have pushed a record of type '${this.internalModel.modelName}' with '${ - this.key - }' as a link, but the value of that link is not a string.`, - typeof link === 'string' || link === null - ); - - this.link = link; - this.fetchPromise = null; - this.setRelationshipIsStale(true); - } - - reload(options) { - if (this._promiseProxy) { - if (this._promiseProxy.get('isPending')) { - return this._promiseProxy; - } - } - - this.setHasFailedLoadAttempt(false); - this.setShouldForceReload(true); - this.getData(options, true); - - return this._promiseProxy; - } - - shouldMakeRequest() { - let { - relationshipIsStale, - hasFailedLoadAttempt, - allInverseRecordsAreLoaded, - hasAnyRelationshipData, - shouldForceReload, - relationshipIsEmpty, - isAsync, - isNew, - fetchPromise, - } = this; - - // never make a request if this record doesn't exist server side yet - if (isNew === true) { - return false; - } - - // do not re-request if we are already awaiting a request - if (fetchPromise !== null) { - return false; - } - - // Always make a request when forced - // failed attempts must call `reload()`. - // - // For legacy reasons, when a relationship is missing only - // some of it's data we rely on individual `findRecord` - // calls which may resolve from cache in the non-link case. - // This determination is made elsewhere. - // - if (shouldForceReload === true || relationshipIsStale === true) { - return !hasFailedLoadAttempt; - } - - // never make a request if we've explicitly attempted to at least once - // since the last update to canonical state - // this includes failed attempts - // e.g. to re-attempt `reload()` must be called force the attempt. - if (hasFailedLoadAttempt === true) { - return false; - } - - // we were explicitly told that there is no inverse relationship - if (relationshipIsEmpty === true) { - return false; - } - - // we were explicitly told what the inverse is, and we have the inverse records available - if (hasAnyRelationshipData === true && allInverseRecordsAreLoaded === true) { - return false; - } - - // if this is a sync relationship, we should not need to fetch, so getting here is an error - assert( - `You looked up the '${this.key}' relationship on a '${ - this.internalModel.type.modelName - }' with id ${ - this.internalModel.id - } but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\`DS.${ - this.relationshipMeta.kind - }({ async: true })\`)`, - isAsync === true - ); - - return true; - } - - _updateLoadingPromise(promise, content) { - if (this._promiseProxy) { - if (content !== undefined) { - this._promiseProxy.set('content', content); - } - this._promiseProxy.set('promise', promise); - } else { - this._promiseProxy = this._createProxy(promise, content); - } - - return this._promiseProxy; - } - - updateInternalModelsFromAdapter(internalModels) { - heimdall.increment(updateInternalModelsFromAdapter); - this.setHasAnyRelationshipData(true); - //TODO(Igor) move this to a proper place - //TODO Once we have adapter support, we need to handle updated and canonical changes - this.computeChanges(internalModels); - } - - notifyRecordRelationshipAdded() {} - - setHasAnyRelationshipData(value) { - this.hasAnyRelationshipData = value; - } - - setHasFailedLoadAttempt(value) { - this.hasFailedLoadAttempt = value; - } - - setRelationshipIsStale(value) { - this.relationshipIsStale = value; - } - - setRelationshipIsEmpty(value) { - this.relationshipIsEmpty = value; - } - - setShouldForceReload(value) { - this.shouldForceReload = value; - } - - /* - `push` for a relationship allows the store to push a JSON API Relationship - Object onto the relationship. The relationship will then extract and set the - meta, data and links of that relationship. - - `push` use `updateMeta`, `updateData` and `updateLink` to update the state - of the relationship. - */ - push(payload, initial) { - heimdall.increment(push); - - let hasRelationshipDataProperty = false; - let hasLink = false; - - if (payload.meta) { - this.updateMeta(payload.meta); - } - - if (payload.data !== undefined) { - hasRelationshipDataProperty = true; - this.updateData(payload.data, initial); - } else if (payload._partialData !== undefined) { - this.updateData(payload._partialData, initial); - } else if (this.isAsync === false) { - hasRelationshipDataProperty = true; - let data = this.kind === 'hasMany' ? [] : null; - - this.updateData(data, initial); - } - - if (payload.links && payload.links.related) { - let relatedLink = _normalizeLink(payload.links.related); - if (relatedLink && relatedLink.href && relatedLink.href !== this.link) { - hasLink = true; - this.updateLink(relatedLink.href); - } - } - - /* - Data being pushed into the relationship might contain only data or links, - or a combination of both. - - IF contains only data - IF contains both links and data - relationshipIsEmpty -> true if is empty array (has-many) or is null (belongs-to) - hasAnyRelationshipData -> true - relationshipIsStale -> false - allInverseRecordsAreLoaded -> run-check-to-determine - - IF contains only links - relationshipIsStale -> true - */ - this.setHasFailedLoadAttempt(false); - if (hasRelationshipDataProperty) { - let relationshipIsEmpty = - payload.data === null || (Array.isArray(payload.data) && payload.data.length === 0); - - this.setHasAnyRelationshipData(true); - this.setRelationshipIsStale(false); - this.setRelationshipIsEmpty(relationshipIsEmpty); - } else if (hasLink) { - this.setRelationshipIsStale(true); - - if (!initial) { - this.internalModel.notifyPropertyChange(this.key); - } - } - } - - _createProxy() {} - - updateData() {} - - destroy() {} -} diff --git a/addon/-legacy-private/system/snapshot.js b/addon/-legacy-private/system/snapshot.js deleted file mode 100644 index 2ff17d9d7de..00000000000 --- a/addon/-legacy-private/system/snapshot.js +++ /dev/null @@ -1,409 +0,0 @@ -/** - @module ember-data -*/ -import { inspect } from '@ember/debug'; -import EmberError from '@ember/error'; -import { get } from '@ember/object'; -import { assign } from '@ember/polyfills'; - -/** - @class Snapshot - @namespace DS - @private - @constructor - @param {DS.Model} internalModel The model to create a snapshot from -*/ -export default class Snapshot { - constructor(internalModel, options = {}) { - this.__attributes = null; - this._belongsToRelationships = Object.create(null); - this._belongsToIds = Object.create(null); - this._hasManyRelationships = Object.create(null); - this._hasManyIds = Object.create(null); - this._internalModel = internalModel; - - /* - If the internalModel does not yet have a record, then we are - likely a snapshot being provided to a find request, so we - populate __attributes lazily. Else, to preserve the "moment - in time" in which a snapshot is created, we greedily grab - the values. - */ - if (internalModel.hasRecord) { - this._attributes; - } - - /**O - The id of the snapshot's underlying record - - Example - - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.id; // => '1' - ``` - - @property id - @type {String} - */ - this.id = internalModel.id; - - /** - A hash of adapter options - @property adapterOptions - @type {Object} - */ - this.adapterOptions = options.adapterOptions; - this.include = options.include; - - /** - The name of the type of the underlying record for this snapshot, as a string. - - @property modelName - @type {String} - */ - this.modelName = internalModel.modelName; - - this._changedAttributes = internalModel.changedAttributes(); - } - - /** - The underlying record for this snapshot. Can be used to access methods and - properties defined on the record. - - Example - - ```javascript - let json = snapshot.record.toJSON(); - ``` - - @property record - @type {DS.Model} - */ - get record() { - return this._internalModel.getRecord(); - } - - get _attributes() { - let attributes = this.__attributes; - - if (attributes === null) { - let record = this.record; - attributes = this.__attributes = Object.create(null); - - record.eachAttribute(keyName => (attributes[keyName] = get(record, keyName))); - } - - return attributes; - } - - /** - The type of the underlying record for this snapshot, as a DS.Model. - - @property type - @type {DS.Model} - */ - get type() { - // TODO @runspired we should deprecate this in favor of modelClass but only once - // we've cleaned up the internals enough that a public change to follow suite is - // uncontroversial. - return this._internalModel.modelClass; - } - - /** - Returns the value of an attribute. - - Example - - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.attr('author'); // => 'Tomster' - postSnapshot.attr('title'); // => 'Ember.js rocks' - ``` - - Note: Values are loaded eagerly and cached when the snapshot is created. - - @method attr - @param {String} keyName - @return {Object} The attribute value or undefined - */ - attr(keyName) { - if (keyName in this._attributes) { - return this._attributes[keyName]; - } - throw new EmberError( - "Model '" + inspect(this.record) + "' has no attribute named '" + keyName + "' defined." - ); - } - - /** - Returns all attributes and their corresponding values. - - Example - - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } - ``` - - @method attributes - @return {Object} All attributes of the current snapshot - */ - attributes() { - return assign({}, this._attributes); - } - - /** - Returns all changed attributes and their old and new values. - - Example - - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postModel.set('title', 'Ember.js rocks!'); - postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } - ``` - - @method changedAttributes - @return {Object} All changed attributes of the current snapshot - */ - changedAttributes() { - let changedAttributes = Object.create(null); - let changedAttributeKeys = Object.keys(this._changedAttributes); - - for (let i = 0, length = changedAttributeKeys.length; i < length; i++) { - let key = changedAttributeKeys[i]; - changedAttributes[key] = this._changedAttributes[key].slice(); - } - - return changedAttributes; - } - - /** - Returns the current value of a belongsTo relationship. - - `belongsTo` takes an optional hash of options as a second parameter, - currently supported options are: - - - `id`: set to `true` if you only want the ID of the related record to be - returned. - - Example - - ```javascript - // store.push('post', { id: 1, title: 'Hello World' }); - // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); - commentSnapshot.belongsTo('post'); // => DS.Snapshot - commentSnapshot.belongsTo('post', { id: true }); // => '1' - - // store.push('comment', { id: 1, body: 'Lorem ipsum' }); - commentSnapshot.belongsTo('post'); // => undefined - ``` - - Calling `belongsTo` will return a new Snapshot as long as there's any known - data for the relationship available, such as an ID. If the relationship is - known but unset, `belongsTo` will return `null`. If the contents of the - relationship is unknown `belongsTo` will return `undefined`. - - Note: Relationships are loaded lazily and cached upon first access. - - @method belongsTo - @param {String} keyName - @param {Object} [options] - @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known - relationship or null if the relationship is known but unset. undefined - will be returned if the contents of the relationship is unknown. - */ - belongsTo(keyName, options) { - let id = options && options.id; - let relationship; - let result; - - if (id && keyName in this._belongsToIds) { - return this._belongsToIds[keyName]; - } - - if (!id && keyName in this._belongsToRelationships) { - return this._belongsToRelationships[keyName]; - } - - relationship = this._internalModel._relationships.get(keyName); - if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { - throw new EmberError( - "Model '" + - inspect(this.record) + - "' has no belongsTo relationship named '" + - keyName + - "' defined." - ); - } - - let { hasAnyRelationshipData, inverseInternalModel } = relationship; - - if (hasAnyRelationshipData) { - if (inverseInternalModel && !inverseInternalModel.isDeleted()) { - if (id) { - result = get(inverseInternalModel, 'id'); - } else { - result = inverseInternalModel.createSnapshot(); - } - } else { - result = null; - } - } - - if (id) { - this._belongsToIds[keyName] = result; - } else { - this._belongsToRelationships[keyName] = result; - } - - return result; - } - - /** - Returns the current value of a hasMany relationship. - - `hasMany` takes an optional hash of options as a second parameter, - currently supported options are: - - - `ids`: set to `true` if you only want the IDs of the related records to be - returned. - - Example - - ```javascript - // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); - postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] - postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] - - // store.push('post', { id: 1, title: 'Hello World' }); - postSnapshot.hasMany('comments'); // => undefined - ``` - - Note: Relationships are loaded lazily and cached upon first access. - - @method hasMany - @param {String} keyName - @param {Object} [options] - @return {(Array|undefined)} An array of snapshots or IDs of a known - relationship or an empty array if the relationship is known but unset. - undefined will be returned if the contents of the relationship is unknown. - */ - hasMany(keyName, options) { - let ids = options && options.ids; - let relationship; - let results; - - if (ids && keyName in this._hasManyIds) { - return this._hasManyIds[keyName]; - } - - if (!ids && keyName in this._hasManyRelationships) { - return this._hasManyRelationships[keyName]; - } - - relationship = this._internalModel._relationships.get(keyName); - if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { - throw new EmberError( - "Model '" + - inspect(this.record) + - "' has no hasMany relationship named '" + - keyName + - "' defined." - ); - } - - let { hasAnyRelationshipData, members } = relationship; - - if (hasAnyRelationshipData) { - results = []; - members.forEach(member => { - if (!member.isDeleted()) { - if (ids) { - results.push(member.id); - } else { - results.push(member.createSnapshot()); - } - } - }); - } - - if (ids) { - this._hasManyIds[keyName] = results; - } else { - this._hasManyRelationships[keyName] = results; - } - - return results; - } - - /** - Iterates through all the attributes of the model, calling the passed - function on each attribute. - - Example - - ```javascript - snapshot.eachAttribute(function(name, meta) { - // ... - }); - ``` - - @method eachAttribute - @param {Function} callback the callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - */ - eachAttribute(callback, binding) { - this.record.eachAttribute(callback, binding); - } - - /** - Iterates through all the relationships of the model, calling the passed - function on each relationship. - - Example - - ```javascript - snapshot.eachRelationship(function(name, relationship) { - // ... - }); - ``` - - @method eachRelationship - @param {Function} callback the callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - */ - eachRelationship(callback, binding) { - this.record.eachRelationship(callback, binding); - } - - /** - Serializes the snapshot using the serializer for the model. - - Example - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - createRecord(store, type, snapshot) { - var data = snapshot.serialize({ includeId: true }); - var url = `/${type.modelName}`; - - return fetch(url, { - method: 'POST', - body: data, - }).then((response) => response.json()) - } - }); - ``` - - @method serialize - @param {Object} options - @return {Object} an object whose values are primitive JSON values only - */ - serialize(options) { - return this.record.store.serializerFor(this.modelName).serialize(this, options); - } -} diff --git a/addon/-legacy-private/system/store.js b/addon/-legacy-private/system/store.js deleted file mode 100644 index e0e61c1a94d..00000000000 --- a/addon/-legacy-private/system/store.js +++ /dev/null @@ -1,3462 +0,0 @@ -/** - @module ember-data -*/ - -import { registerWaiter, unregisterWaiter } from '@ember/test'; - -import { A } from '@ember/array'; -import EmberError from '@ember/error'; -import MapWithDefault from './map-with-default'; -import { run as emberRunLoop } from '@ember/runloop'; -import { set, get, computed } from '@ember/object'; -import { assign } from '@ember/polyfills'; -import { default as RSVP, Promise } from 'rsvp'; -import Service from '@ember/service'; -import { typeOf, isPresent, isNone } from '@ember/utils'; -import Ember from 'ember'; -import { InvalidError } from '../adapters/errors'; -import { instrument } from 'ember-data/-debug'; -import { assert, deprecate, warn, inspect } from '@ember/debug'; -import { DEBUG } from '@glimmer/env'; -import Model from './model/model'; -import normalizeModelName from './normalize-model-name'; -import IdentityMap from './identity-map'; - -import { promiseArray, promiseObject } from './promise-proxies'; - -import { _bind, _guard, _objectIsAlive, guardDestroyedStore } from './store/common'; - -import { normalizeResponseHelper } from './store/serializer-response'; -import { serializerForAdapter } from './store/serializers'; -import RelationshipPayloadsManager from './relationships/relationship-payloads-manager'; - -import { - _find, - _findMany, - _findHasMany, - _findBelongsTo, - _findAll, - _query, - _queryRecord, -} from './store/finders'; - -import { getOwner } from '../utils'; -import coerceId from './coerce-id'; -import RecordArrayManager from './record-array-manager'; -import InternalModel from './model/internal-model'; -import edBackburner from './backburner'; - -const badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; -const emberRun = emberRunLoop.backburner; -const { ENV } = Ember; - -//Get the materialized model from the internalModel/promise that returns -//an internal model and return it in a promiseObject. Useful for returning -//from find methods -function promiseRecord(internalModelPromise, label) { - let toReturn = internalModelPromise.then(internalModel => internalModel.getRecord()); - - return promiseObject(toReturn, label); -} - -let Store; - -// Implementors Note: -// -// The variables in this file are consistently named according to the following -// scheme: -// -// * +id+ means an identifier managed by an external source, provided inside -// the data provided by that source. These are always coerced to be strings -// before being used internally. -// * +clientId+ means a transient numerical identifier generated at runtime by -// the data store. It is important primarily because newly created objects may -// not yet have an externally generated id. -// * +internalModel+ means a record internalModel object, which holds metadata about a -// record, even if it has not yet been fully materialized. -// * +type+ means a DS.Model. - -const { - _generateId, - _internalModelForId, - _load, - _pushInternalModel, - _setupRelationships, - adapterFor, - _buildInternalModel, - _didUpdateAll, - normalize, - peekAll, - peekRecord, - serializerFor, - _internalModelsFor, -} = heimdall.registerMonitor( - 'store', - '_generateId', - '_internalModelForId', - '_load', - '_pushInternalModel', - '_setupRelationships', - 'adapterFor', - '_buildInternalModel', - '_didUpdateAll', - 'normalize', - 'peekAll', - 'peekRecord', - 'serializerFor', - '_internalModelsFor' -); - -/** - The store contains all of the data for records loaded from the server. - It is also responsible for creating instances of `DS.Model` that wrap - the individual data for a record, so that they can be bound to in your - Handlebars templates. - - Define your application's store like this: - - ```app/services/store.js - import DS from 'ember-data'; - - export default DS.Store.extend({ - }); - ``` - - Most Ember.js applications will only have a single `DS.Store` that is - automatically created by their `Ember.Application`. - - You can retrieve models from the store in several ways. To retrieve a record - for a specific id, use `DS.Store`'s `findRecord()` method: - - ```javascript - store.findRecord('person', 123).then(function (person) { - }); - ``` - - By default, the store will talk to your backend using a standard - REST mechanism. You can customize how the store talks to your - backend by specifying a custom adapter: - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - }); - ``` - - You can learn more about writing a custom adapter by reading the `DS.Adapter` - documentation. - - ### Store createRecord() vs. push() vs. pushPayload() - - The store provides multiple ways to create new record objects. They have - some subtle differences in their use which are detailed below: - - [createRecord](#method_createRecord) is used for creating new - records on the client side. This will return a new record in the - `created.uncommitted` state. In order to persist this record to the - backend, you will need to call `record.save()`. - - [push](#method_push) is used to notify Ember Data's store of new or - updated records that exist in the backend. This will return a record - in the `loaded.saved` state. The primary use-case for `store#push` is - to notify Ember Data about record updates (full or partial) that happen - outside of the normal adapter methods (for example - [SSE](http://dev.w3.org/html5/eventsource/) or [Web - Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). - - [pushPayload](#method_pushPayload) is a convenience wrapper for - `store#push` that will deserialize payloads if the - Serializer implements a `pushPayload` method. - - Note: When creating a new record using any of the above methods - Ember Data will update `DS.RecordArray`s such as those returned by - `store#peekAll()` or `store#findAll()`. This means any - data bindings or computed properties that depend on the RecordArray - will automatically be synced to include the new or updated record - values. - - @class Store - @namespace DS - @extends Ember.Service -*/ -Store = Service.extend({ - /** - @method init - @private - */ - init() { - this._super(...arguments); - this._backburner = edBackburner; - // internal bookkeeping; not observable - this.recordArrayManager = new RecordArrayManager({ store: this }); - this._identityMap = new IdentityMap(); - this._pendingSave = []; - this._modelFactoryCache = Object.create(null); - this._relationshipsPayloads = new RelationshipPayloadsManager(this); - - /* - Ember Data uses several specialized micro-queues for organizing - and coalescing similar async work. - - These queues are currently controlled by a flush scheduled into - ember-data's custom backburner instance. - */ - // used for coalescing record save requests - this._pendingSave = []; - // used for coalescing relationship updates - this._updatedRelationships = []; - // used for coalescing relationship setup needs - this._pushedInternalModels = []; - // used for coalescing internal model updates - this._updatedInternalModels = []; - - // used to keep track of all the find requests that need to be coalesced - this._pendingFetch = new MapWithDefault({ - defaultValue() { - return []; - }, - }); - - this._adapterCache = Object.create(null); - this._serializerCache = Object.create(null); - - if (DEBUG) { - this.shouldAssertMethodCallsOnDestroyedStore = - this.shouldAssertMethodCallsOnDestroyedStore || false; - if (this.shouldTrackAsyncRequests === undefined) { - this.shouldTrackAsyncRequests = false; - } - if (this.generateStackTracesForTrackedRequests === undefined) { - this.generateStackTracesForTrackedRequests = false; - } - - this._trackedAsyncRequests = []; - this._trackAsyncRequestStart = label => { - let trace = - 'set `store.generateStackTracesForTrackedRequests = true;` to get a detailed trace for where this request originated'; - - if (this.generateStackTracesForTrackedRequests) { - try { - throw new Error(`EmberData TrackedRequest: ${label}`); - } catch (e) { - trace = e; - } - } - - let token = Object.freeze({ - label, - trace, - }); - - this._trackedAsyncRequests.push(token); - return token; - }; - this._trackAsyncRequestEnd = token => { - let index = this._trackedAsyncRequests.indexOf(token); - - if (index === -1) { - throw new Error( - `Attempted to end tracking for the following request but it was not being tracked:\n${token}` - ); - } - - this._trackedAsyncRequests.splice(index, 1); - }; - - this.__asyncWaiter = () => { - let shouldTrack = this.shouldTrackAsyncRequests; - let tracked = this._trackedAsyncRequests; - let isSettled = tracked.length === 0; - - return shouldTrack !== true || isSettled; - }; - - registerWaiter(this.__asyncWaiter); - } - }, - - /** - The default adapter to use to communicate to a backend server or - other persistence layer. This will be overridden by an application - adapter if present. - - If you want to specify `app/adapters/custom.js` as a string, do: - - ```js - import DS from 'ember-data'; - - export default DS.Store.extend({ - adapter: 'custom', - }); - ``` - - @property adapter - @default '-json-api' - @type {String} - */ - adapter: '-json-api', - - /** - This property returns the adapter, after resolving a possible - string key. - - If the supplied `adapter` was a class, or a String property - path resolved to a class, this property will instantiate the - class. - - This property is cacheable, so the same instance of a specified - adapter class should be used for the lifetime of the store. - - @property defaultAdapter - @private - @return DS.Adapter - */ - defaultAdapter: computed('adapter', function() { - let adapter = get(this, 'adapter'); - - assert( - 'You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', - typeof adapter === 'string' - ); - - return this.adapterFor(adapter); - }), - - // ..................... - // . CREATE NEW RECORD . - // ..................... - - /** - Create a new record in the current store. The properties passed - to this method are set on the newly created record. - - To create a new instance of a `Post`: - - ```js - store.createRecord('post', { - title: 'Rails is omakase' - }); - ``` - - To create a new instance of a `Post` that has a relationship with a `User` record: - - ```js - let user = this.store.peekRecord('user', 1); - store.createRecord('post', { - title: 'Rails is omakase', - user: user - }); - ``` - - @method createRecord - @param {String} modelName - @param {Object} inputProperties a hash of properties to set on the - newly created record. - @return {DS.Model} record - */ - createRecord(modelName, inputProperties) { - if (DEBUG) { - assertDestroyingStore(this, 'createRecord'); - } - assert( - `You need to pass a model name to the store's createRecord method`, - isPresent(modelName) - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - // This is wrapped in a `run.join` so that in test environments users do not need to manually wrap - // calls to `createRecord`. The run loop usage here is because we batch the joining and updating - // of record-arrays via ember's run loop, not our own. - // - // to remove this, we would need to move to a new `async` API. - return emberRun.join(() => { - return this._backburner.join(() => { - let normalizedModelName = normalizeModelName(modelName); - let properties = assign({}, inputProperties); - - // If the passed properties do not include a primary key, - // give the adapter an opportunity to generate one. Typically, - // client-side ID generators will use something like uuid.js - // to avoid conflicts. - - if (isNone(properties.id)) { - properties.id = this._generateId(normalizedModelName, properties); - } - - // Coerce ID to a string - properties.id = coerceId(properties.id); - - let internalModel = this._buildInternalModel(normalizedModelName, properties.id); - internalModel.loadedData(); - return internalModel.getRecord(properties); - }); - }); - }, - - /** - If possible, this method asks the adapter to generate an ID for - a newly created record. - - @method _generateId - @private - @param {String} modelName - @param {Object} properties from the new record - @return {String} if the adapter can generate one, an ID - */ - _generateId(modelName, properties) { - heimdall.increment(_generateId); - let adapter = this.adapterFor(modelName); - - if (adapter && adapter.generateIdForRecord) { - return adapter.generateIdForRecord(this, modelName, properties); - } - - return null; - }, - - // ................. - // . DELETE RECORD . - // ................. - - /** - For symmetry, a record can be deleted via the store. - - Example - - ```javascript - let post = store.createRecord('post', { - title: 'Rails is omakase' - }); - - store.deleteRecord(post); - ``` - - @method deleteRecord - @param {DS.Model} record - */ - deleteRecord(record) { - if (DEBUG) { - assertDestroyingStore(this, 'deleteRecord'); - } - record.deleteRecord(); - }, - - /** - For symmetry, a record can be unloaded via the store. - This will cause the record to be destroyed and freed up for garbage collection. - - Example - - ```javascript - store.findRecord('post', 1).then(function(post) { - store.unloadRecord(post); - }); - ``` - - @method unloadRecord - @param {DS.Model} record - */ - unloadRecord(record) { - if (DEBUG) { - assertDestroyingStore(this, 'unloadRecord'); - } - record.unloadRecord(); - }, - - // ................ - // . FIND RECORDS . - // ................ - - /** - @method find - @param {String} modelName - @param {String|Integer} id - @param {Object} options - @return {Promise} promise - @private - */ - find(modelName, id, options) { - if (DEBUG) { - assertDestroyingStore(this, 'find'); - } - // The default `model` hook in Route calls `find(modelName, id)`, - // that's why we have to keep this method around even though `findRecord` is - // the public way to get a record by modelName and id. - assert( - `Using store.find(type) has been removed. Use store.findAll(modelName) to retrieve all records for a given type.`, - arguments.length !== 1 - ); - assert( - `Calling store.find(modelName, id, { preload: preload }) is no longer supported. Use store.findRecord(modelName, id, { preload: preload }) instead.`, - !options - ); - assert( - `You need to pass the model name and id to the store's find method`, - arguments.length === 2 - ); - assert( - `You cannot pass '${id}' as id to the store's find method`, - typeof id === 'string' || typeof id === 'number' - ); - assert( - `Calling store.find() with a query object is no longer supported. Use store.query() instead.`, - typeof id !== 'object' - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - return this.findRecord(modelName, id); - }, - - /** - This method returns a record for a given type and id combination. - - The `findRecord` method will always resolve its promise with the same - object for a given type and `id`. - - The `findRecord` method will always return a **promise** that will be - resolved with the record. - - Example - - ```app/routes/post.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - model(params) { - return this.store.findRecord('post', params.post_id); - } - }); - ``` - - 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. - - ### Preloading - - You can optionally `preload` specific attributes and relationships that you know of - by passing them via the passed `options`. - - For example, if your Ember route looks like `/posts/1/comments/2` and your API route - for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment - without fetching the post you can pass in the post to the `findRecord` call: - - ```javascript - store.findRecord('comment', 2, { preload: { post: 1 } }); - ``` - - If you have access to the post model you can also pass the model itself: - - ```javascript - store.findRecord('post', 1).then(function (myPostModel) { - store.findRecord('comment', 2, { post: myPostModel }); - }); - ``` - - ### 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: - - ```js - store.push({ - data: { - id: 1, - type: 'post', - revision: 1 - } - }); - - // adapter#findRecord resolves with - // [ - // { - // id: 1, - // type: 'post', - // revision: 2 - // } - // ] - store.findRecord('post', 1, { reload: true }).then(function(post) { - 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 - import ApplicationAdapter from "./application"; - - export default ApplicationAdapter.extend({ - shouldReloadRecord(store, snapshot) { - return false; - }, - - shouldBackgroundReloadRecord(store, snapshot) { - return true; - } - }); - - // ... - - store.push({ - data: { - id: 1, - type: 'post', - revision: 1 - } - }); - - let blogPost = store.findRecord('post', 1).then(function(post) { - post.get('revision'); // 1 - }); - - // later, once adapter#findRecord resolved with - // [ - // { - // id: 1, - // type: 'post', - // 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 Route from '@ember/routing/route'; - - export default Route.extend({ - model(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 Route from '@ember/routing/route'; - - export default Route.extend({ - model(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(store, type, id, snapshot) { - if (snapshot.adapterOptions.subscribe) { - // ... - } - // ... - } - }); - ``` - - See [peekRecord](#method_peekRecord) to get the cached version of a record. - - ### Retrieving Related Model Records - - If you use an adapter such as Ember's default - [`JSONAPIAdapter`](https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) - that supports the [JSON API specification](http://jsonapi.org/) and if your server - endpoint supports the use of an - ['include' query parameter](http://jsonapi.org/format/#fetching-includes), - you can use `findRecord()` to automatically retrieve additional records related to - the one you request by supplying an `include` parameter in the `options` object. - - For example, given a `post` model that has a `hasMany` relationship with a `comment` - model, when we retrieve a specific post we can have the server also return that post's - comments in the same request: - - ```app/routes/post.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - model(params) { - return this.store.findRecord('post', params.post_id, { include: 'comments' }); - } - }); - - ``` - In this case, the post's comments would then be available in your template as - `model.comments`. - - Multiple relationships can be requested using an `include` parameter consisting of a - comma-separated list (without white-space) while nested relationships can be specified - using a dot-separated sequence of relationship names. So to request both the post's - comments and the authors of those comments the request would look like this: - - ```app/routes/post.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - model(params) { - return this.store.findRecord('post', params.post_id, { include: 'comments,comments.author' }); - } - }); - - ``` - - @since 1.13.0 - @method findRecord - @param {String} modelName - @param {(String|Integer)} id - @param {Object} options - @return {Promise} promise - */ - findRecord(modelName, id, options) { - if (DEBUG) { - assertDestroyingStore(this, 'findRecord'); - } - assert(`You need to pass a model name to the store's findRecord method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - assert( - badIdFormatAssertion, - (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && !isNaN(id)) - ); - - let normalizedModelName = normalizeModelName(modelName); - - let internalModel = this._internalModelForId(normalizedModelName, id); - options = options || {}; - - if (!this.hasRecordForId(normalizedModelName, id)) { - return this._findByInternalModel(internalModel, options); - } - - let fetchedInternalModel = this._findRecord(internalModel, options); - - return promiseRecord( - fetchedInternalModel, - `DS: Store#findRecord ${normalizedModelName} with id: ${id}` - ); - }, - - _findRecord(internalModel, options) { - // Refetch if the reload option is passed - if (options.reload) { - return this._scheduleFetch(internalModel, options); - } - - let snapshot = internalModel.createSnapshot(options); - let adapter = this.adapterFor(internalModel.modelName); - - // Refetch the record if the adapter thinks the record is stale - if (adapter.shouldReloadRecord(this, snapshot)) { - return this._scheduleFetch(internalModel, options); - } - - 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); - }, - - _findByInternalModel(internalModel, options = {}) { - if (options.preload) { - internalModel.preloadData(options.preload); - } - - let fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); - - return promiseRecord( - fetchedInternalModel, - `DS: Store#findRecord ${internalModel.modelName} with id: ${internalModel.id}` - ); - }, - - _findEmptyInternalModel(internalModel, options) { - if (internalModel.isEmpty()) { - return this._scheduleFetch(internalModel, options); - } - - //TODO double check about reloading - if (internalModel.isLoading()) { - return internalModel._promiseProxy; - } - - return Promise.resolve(internalModel); - }, - - /** - This method makes a series of requests to the adapter's `find` method - and returns a promise that resolves once they are all loaded. - - @private - @method findByIds - @param {String} modelName - @param {Array} ids - @return {Promise} promise - */ - findByIds(modelName, ids) { - if (DEBUG) { - assertDestroyingStore(this, 'findByIds'); - } - assert(`You need to pass a model name to the store's findByIds method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let promises = new Array(ids.length); - - let normalizedModelName = normalizeModelName(modelName); - - for (let i = 0; i < ids.length; i++) { - promises[i] = this.findRecord(normalizedModelName, ids[i]); - } - - return promiseArray( - RSVP.all(promises).then(A, null, `DS: Store#findByIds of ${normalizedModelName} complete`) - ); - }, - - /** - This method is called by `findRecord` if it discovers that a particular - type/id pair hasn't been loaded yet to kick off a request to the - adapter. - - @method _fetchRecord - @private - @param {InternalModel} internalModel model - @return {Promise} promise - */ - _fetchRecord(internalModel, options) { - let modelName = internalModel.modelName; - let adapter = this.adapterFor(modelName); - - assert(`You tried to find a record but you have no adapter (for ${modelName})`, adapter); - assert( - `You tried to find a record but your adapter (for ${modelName}) does not implement 'findRecord'`, - typeof adapter.findRecord === 'function' - ); - - return _find(adapter, this, internalModel.type, internalModel.id, internalModel, options); - }, - - _scheduleFetchMany(internalModels, options) { - let fetches = new Array(internalModels.length); - - for (let i = 0; i < internalModels.length; i++) { - fetches[i] = this._scheduleFetch(internalModels[i], options); - } - - return Promise.all(fetches); - }, - - _scheduleFetch(internalModel, options) { - if (internalModel._promiseProxy) { - return internalModel._promiseProxy; - } - - let { id, modelName } = internalModel; - let resolver = RSVP.defer(`Fetching ${modelName}' with id: ${id}`); - let pendingFetchItem = { - internalModel, - resolver, - options, - }; - - if (DEBUG) { - if (this.generateStackTracesForTrackedRequests === true) { - let trace; - - try { - throw new Error(`Trace Origin for scheduled fetch for ${modelName}:${id}.`); - } catch (e) { - trace = e; - } - - // enable folks to discover the origin of this findRecord call when - // debugging. Ideally we would have a tracked queue for requests with - // labels or local IDs that could be used to merge this trace with - // the trace made available when we detect an async leak - pendingFetchItem.trace = trace; - } - } - - let promise = resolver.promise; - - internalModel.loadingData(promise); - if (this._pendingFetch.size === 0) { - emberRun.schedule('actions', this, this.flushAllPendingFetches); - } - - this._pendingFetch.get(modelName).push(pendingFetchItem); - - return promise; - }, - - flushAllPendingFetches() { - if (this.isDestroyed || this.isDestroying) { - return; - } - - this._pendingFetch.forEach(this._flushPendingFetchForType, this); - this._pendingFetch.clear(); - }, - - _flushPendingFetchForType(pendingFetchItems, modelName) { - let store = this; - let adapter = store.adapterFor(modelName); - let shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; - let totalItems = pendingFetchItems.length; - let internalModels = new Array(totalItems); - let seeking = Object.create(null); - - let optionsMap = new WeakMap(); - - for (let i = 0; i < totalItems; i++) { - let pendingItem = pendingFetchItems[i]; - let internalModel = pendingItem.internalModel; - internalModels[i] = internalModel; - optionsMap.set(internalModel, pendingItem.options); - seeking[internalModel.id] = pendingItem; - } - - for (let i = 0; i < totalItems; i++) { - let internalModel = internalModels[i]; - // We may have unloaded the record after scheduling this fetch, in which - // case we must cancel the destroy. This is because we require a record - // to build a snapshot. This is not fundamental: this cancelation code - // can be removed when snapshots can be created for internal models that - // have no records. - if (internalModel.hasScheduledDestroy()) { - internalModels[i].cancelDestroy(); - } - } - - function _fetchRecord(recordResolverPair) { - let recordFetch = store._fetchRecord( - recordResolverPair.internalModel, - recordResolverPair.options - ); - - recordResolverPair.resolver.resolve(recordFetch); - } - - function handleFoundRecords(foundInternalModels, expectedInternalModels) { - // resolve found records - let found = Object.create(null); - for (let i = 0, l = foundInternalModels.length; i < l; i++) { - let internalModel = foundInternalModels[i]; - let pair = seeking[internalModel.id]; - found[internalModel.id] = internalModel; - - if (pair) { - let resolver = pair.resolver; - resolver.resolve(internalModel); - } - } - - // reject missing records - let missingInternalModels = []; - - for (let i = 0, l = expectedInternalModels.length; i < l; i++) { - let internalModel = expectedInternalModels[i]; - - if (!found[internalModel.id]) { - missingInternalModels.push(internalModel); - } - } - - if (missingInternalModels.length) { - warn( - 'Ember Data expected to find records with the following ids in the adapter response but they were missing: [ "' + - missingInternalModels.map(r => r.id).join('", "') + - '" ]', - false, - { - id: 'ds.store.missing-records-from-adapter', - } - ); - rejectInternalModels(missingInternalModels); - } - } - - function rejectInternalModels(internalModels, error) { - for (let i = 0, l = internalModels.length; i < l; i++) { - let internalModel = internalModels[i]; - let pair = seeking[internalModel.id]; - - if (pair) { - pair.resolver.reject( - error || - new Error( - `Expected: '${internalModel}' to be present in the adapter provided payload, but it was not found.` - ) - ); - } - } - } - - if (shouldCoalesce) { - // TODO: Improve records => snapshots => records => snapshots - // - // We want to provide records to all store methods and snapshots to all - // adapter methods. To make sure we're doing that we're providing an array - // of snapshots to adapter.groupRecordsForFindMany(), which in turn will - // return grouped snapshots instead of grouped records. - // - // But since the _findMany() finder is a store method we need to get the - // records from the grouped snapshots even though the _findMany() finder - // will once again convert the records to snapshots for adapter.findMany() - let snapshots = new Array(totalItems); - for (let i = 0; i < totalItems; i++) { - let internalModel = internalModels[i]; - snapshots[i] = internalModel.createSnapshot(optionsMap.get(internalModel)); - } - - let groups = adapter.groupRecordsForFindMany(this, snapshots); - - for (var i = 0, l = groups.length; i < l; i++) { - var group = groups[i]; - var totalInGroup = groups[i].length; - var ids = new Array(totalInGroup); - var groupedInternalModels = new Array(totalInGroup); - - for (var j = 0; j < totalInGroup; j++) { - var internalModel = group[j]._internalModel; - - groupedInternalModels[j] = internalModel; - ids[j] = internalModel.id; - } - - if (totalInGroup > 1) { - (function(groupedInternalModels) { - _findMany(adapter, store, modelName, ids, groupedInternalModels, optionsMap) - .then(function(foundInternalModels) { - handleFoundRecords(foundInternalModels, groupedInternalModels); - }) - .catch(function(error) { - rejectInternalModels(groupedInternalModels, error); - }); - })(groupedInternalModels); - } else if (ids.length === 1) { - var pair = seeking[groupedInternalModels[0].id]; - _fetchRecord(pair); - } else { - assert( - "You cannot return an empty array from adapter's method groupRecordsForFindMany", - false - ); - } - } - } else { - for (let i = 0; i < totalItems; i++) { - _fetchRecord(pendingFetchItems[i]); - } - } - }, - - /** - Get the reference for the specified record. - - Example - - ```javascript - let userRef = store.getReference('user', 1); - - // check if the user is loaded - let isLoaded = userRef.value() !== null; - - // get the record of the reference (null if not yet available) - let user = userRef.value(); - - // get the identifier of the reference - if (userRef.remoteType() === 'id') { - let 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} modelName - @param {String|Integer} id - @since 2.5.0 - @return {RecordReference} - */ - getReference(modelName, id) { - if (DEBUG) { - assertDestroyingStore(this, 'getReference'); - } - let normalizedModelName = normalizeModelName(modelName); - - return this._internalModelForId(normalizedModelName, 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. - - See [findRecord](#method_findRecord) if you would like to request this record from the backend. - - _Note: This is a synchronous method and does not return a promise._ - - ```js - let post = store.peekRecord('post', 1); - - post.get('id'); // 1 - ``` - - @since 1.13.0 - @method peekRecord - @param {String} modelName - @param {String|Integer} id - @return {DS.Model|null} record - */ - peekRecord(modelName, id) { - if (DEBUG) { - assertDestroyingStore(this, 'peekRecord'); - } - heimdall.increment(peekRecord); - assert(`You need to pass a model name to the store's peekRecord method`, isPresent(modelName)); - assert( - `You need to pass both a model name and id to the store's peekRecord method`, - isPresent(modelName) && isPresent(id) - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - - if (this.hasRecordForId(normalizedModelName, id)) { - return this._internalModelForId(normalizedModelName, id).getRecord(); - } else { - return null; - } - }, - - /** - This method is called by the record's `reload` method. - - This method calls the adapter's `find` method, which returns a promise. When - **that** promise resolves, `_reloadRecord` will resolve the promise returned - by the record's `reload`. - - @method _reloadRecord - @private - @param {DS.Model} internalModel - @param options optional to include adapterOptions - @return {Promise} promise - */ - _reloadRecord(internalModel, options) { - let { id, modelName } = internalModel; - let adapter = this.adapterFor(modelName); - - assert(`You cannot reload a record without an ID`, id); - assert(`You tried to reload a record but you have no adapter (for ${modelName})`, adapter); - assert( - `You tried to reload a record but your adapter does not implement 'findRecord'`, - typeof adapter.findRecord === 'function' || typeof adapter.find === 'function' - ); - - return this._scheduleFetch(internalModel, options); - }, - - /** - This method returns true if a record for a given modelName and id is already - loaded in the store. Use this function to know beforehand if a findRecord() - will result in a request or that it will be a cache hit. - - Example - - ```javascript - store.hasRecordForId('post', 1); // false - store.findRecord('post', 1).then(function() { - store.hasRecordForId('post', 1); // true - }); - ``` - - @method hasRecordForId - @param {String} modelName - @param {(String|Integer)} id - @return {Boolean} - */ - hasRecordForId(modelName, id) { - if (DEBUG) { - assertDestroyingStore(this, 'hasRecordForId'); - } - assert( - `You need to pass a model name to the store's hasRecordForId method`, - isPresent(modelName) - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let normalizedModelName = normalizeModelName(modelName); - - let trueId = coerceId(id); - let internalModel = this._internalModelsFor(normalizedModelName).get(trueId); - - return !!internalModel && internalModel.isLoaded(); - }, - - /** - Returns id record for a given type and ID. If one isn't already loaded, - it builds a new record and leaves it in the `empty` state. - - @method recordForId - @private - @param {String} modelName - @param {(String|Integer)} id - @return {DS.Model} record - */ - recordForId(modelName, id) { - if (DEBUG) { - assertDestroyingStore(this, 'recordForId'); - } - assert(`You need to pass a model name to the store's recordForId method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - return this._internalModelForId(modelName, id).getRecord(); - }, - - _internalModelForId(modelName, id) { - heimdall.increment(_internalModelForId); - let trueId = coerceId(id); - let internalModel = this._internalModelsFor(modelName).get(trueId); - - if (internalModel) { - // unloadRecord is async, if one attempts to unload + then sync push, - // we must ensure the unload is canceled before continuing - // The createRecord path will take _existingInternalModelForId() - // which will call `destroySync` instead for this unload + then - // sync createRecord scenario. Once we have true client-side - // delete signaling, we should never call destroySync - if (internalModel.hasScheduledDestroy()) { - internalModel.cancelDestroy(); - } - - return internalModel; - } - - return this._buildInternalModel(modelName, trueId); - }, - - _internalModelDidReceiveRelationshipData(modelName, id, relationshipData) { - this._relationshipsPayloads.push(modelName, id, relationshipData); - }, - - _internalModelDestroyed(internalModel) { - this._removeFromIdMap(internalModel); - - if (!this.isDestroying) { - this._relationshipsPayloads.unload(internalModel.modelName, internalModel.id); - } - }, - - /** - @method findMany - @private - @param {Array} internalModels - @return {Promise} promise - */ - findMany(internalModels, options) { - if (DEBUG) { - assertDestroyingStore(this, 'findMany'); - } - let finds = new Array(internalModels.length); - - for (let i = 0; i < internalModels.length; i++) { - finds[i] = this._findEmptyInternalModel(internalModels[i], options); - } - - return Promise.all(finds); - }, - - /** - If a relationship was originally populated by the adapter as a link - (as opposed to a list of IDs), this method is called when the - relationship is fetched. - - The link (which is usually a URL) is passed through unchanged, so the - adapter can make whatever request it wants. - - The usual use-case is for the server to register a URL as a link, and - then use that URL in the future to make a request for the relationship. - - @method findHasMany - @private - @param {InternalModel} internalModel - @param {any} link - @param {(Relationship)} relationship - @return {Promise} promise - */ - findHasMany(internalModel, link, relationship, options) { - if (DEBUG) { - assertDestroyingStore(this, 'findHasMany'); - } - let adapter = this.adapterFor(internalModel.modelName); - - assert( - `You tried to load a hasMany relationship but you have no adapter (for ${ - internalModel.modelName - })`, - adapter - ); - assert( - `You tried to load a hasMany relationship from a specified 'link' in the original payload but your adapter does not implement 'findHasMany'`, - typeof adapter.findHasMany === 'function' - ); - - return _findHasMany(adapter, this, internalModel, link, relationship, options); - }, - - /** - @method findBelongsTo - @private - @param {InternalModel} internalModel - @param {any} link - @param {Relationship} relationship - @return {Promise} promise - */ - findBelongsTo(internalModel, link, relationship, options) { - if (DEBUG) { - assertDestroyingStore(this, 'findBelongsTo'); - } - let adapter = this.adapterFor(internalModel.modelName); - - assert( - `You tried to load a belongsTo relationship but you have no adapter (for ${ - internalModel.modelName - })`, - adapter - ); - assert( - `You tried to load a belongsTo relationship from a specified 'link' in the original payload but your adapter does not implement 'findBelongsTo'`, - typeof adapter.findBelongsTo === 'function' - ); - - return _findBelongsTo(adapter, this, internalModel, link, relationship, options); - }, - - /** - This method delegates a query to the adapter. This is the one place where - adapter-level semantics are exposed to the application. - - Each time this method is called a new request is made through the adapter. - - Exposing queries this way seems preferable to creating an abstract query - language for all server-side queries, and then require all adapters to - implement them. - - --- - - If you do something like this: - - ```javascript - store.query('person', { page: 1 }); - ``` - - The call made to the server, using a Rails backend, will look something like this: - - ``` - Started GET "/api/v1/person?page=1" - Processing by Api::V1::PersonsController#index as HTML - Parameters: { "page"=>"1" } - ``` - - --- - - If you do something like this: - - ```javascript - store.query('person', { ids: [1, 2, 3] }); - ``` - - The call to the server, using a Rails backend, will look something like this: - - ``` - Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" - Processing by Api::V1::PersonsController#index as HTML - Parameters: { "ids" => ["1", "2", "3"] } - ``` - - This method returns a promise, which is resolved with an - [`AdapterPopulatedRecordArray`](https://emberjs.com/api/data/classes/DS.AdapterPopulatedRecordArray.html) - once the server returns. - - @since 1.13.0 - @method query - @param {String} modelName - @param {any} query an opaque query to be used by the adapter - @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter.query - @return {Promise} promise - */ - query(modelName, query, options) { - if (DEBUG) { - assertDestroyingStore(this, 'query'); - } - assert(`You need to pass a model name to the store's query method`, isPresent(modelName)); - assert(`You need to pass a query hash to the store's query method`, query); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let adapterOptionsWrapper = {}; - - if (options && options.adapterOptions) { - adapterOptionsWrapper.adapterOptions = options.adapterOptions; - } - - let normalizedModelName = normalizeModelName(modelName); - return this._query(normalizedModelName, query, null, adapterOptionsWrapper); - }, - - _query(modelName, query, array, options) { - let token = heimdall.start('store._query'); - assert(`You need to pass a model name to the store's query method`, isPresent(modelName)); - assert(`You need to pass a query hash to the store's query method`, query); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let modelToken = heimdall.start('initial-modelFor-lookup'); - heimdall.stop(modelToken); - - let adapterToken = heimdall.start('initial-adapterFor-lookup'); - let adapter = this.adapterFor(modelName); - heimdall.stop(adapterToken); - - assert(`You tried to load a query but you have no adapter (for ${modelName})`, adapter); - assert( - `You tried to load a query but your adapter does not implement 'query'`, - typeof adapter.query === 'function' - ); - - let pA = promiseArray(_query(adapter, this, modelName, query, array, options)); - instrument(() => { - pA.finally(() => { - heimdall.stop(token); - }); - }); - return pA; - }, - - /** - This method makes a request for one record, where the `id` is not known - beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) - instead). - - This method can be used when it is certain that the server will return a - single object for the primary data. - - Each time this method is called a new request is made through the adapter. - - Let's assume our API provides an endpoint for the currently logged in user - via: - - ``` - // GET /api/current_user - { - user: { - id: 1234, - username: 'admin' - } - } - ``` - - Since the specific `id` of the `user` is not known beforehand, we can use - `queryRecord` to get the user: - - ```javascript - store.queryRecord('user', {}).then(function(user) { - let username = user.get('username'); - console.log(`Currently logged in as ${username}`); - }); - ``` - - The request is made through the adapters' `queryRecord`: - - ```app/adapters/user.js - import $ from 'jquery'; - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - queryRecord(modelName, query) { - return $.getJSON('/api/current_user'); - } - }); - ``` - - Note: the primary use case for `store.queryRecord` is when a single record - is queried and the `id` is not known beforehand. In all other cases - `store.query` and using the first item of the array is likely the preferred - way: - - ``` - // GET /users?username=unique - { - data: [{ - id: 1234, - type: 'user', - attributes: { - username: "unique" - } - }] - } - ``` - - ```javascript - store.query('user', { username: 'unique' }).then(function(users) { - return users.get('firstObject'); - }).then(function(user) { - let id = user.get('id'); - }); - ``` - - This method returns a promise, which resolves with the found record. - - If the adapter returns no data for the primary data of the payload, then - `queryRecord` resolves with `null`: - - ``` - // GET /users?username=unique - { - data: null - } - ``` - - ```javascript - store.queryRecord('user', { username: 'unique' }).then(function(user) { - console.log(user); // null - }); - ``` - - @since 1.13.0 - @method queryRecord - @param {String} modelName - @param {any} query an opaque query to be used by the adapter - @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter.queryRecord - @return {Promise} promise which resolves with the found record or `null` - */ - queryRecord(modelName, query, options) { - if (DEBUG) { - assertDestroyingStore(this, 'queryRecord'); - } - assert(`You need to pass a model name to the store's queryRecord method`, isPresent(modelName)); - assert(`You need to pass a query hash to the store's queryRecord method`, query); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let normalizedModelName = normalizeModelName(modelName); - let adapter = this.adapterFor(normalizedModelName); - let adapterOptionsWrapper = {}; - - if (options && options.adapterOptions) { - adapterOptionsWrapper.adapterOptions = options.adapterOptions; - } - - assert( - `You tried to make a query but you have no adapter (for ${normalizedModelName})`, - adapter - ); - assert( - `You tried to make a query but your adapter does not implement 'queryRecord'`, - typeof adapter.queryRecord === 'function' - ); - - return promiseObject( - _queryRecord(adapter, this, normalizedModelName, query, adapterOptionsWrapper).then( - internalModel => { - // the promise returned by store.queryRecord is expected to resolve with - // an instance of DS.Model - if (internalModel) { - return internalModel.getRecord(); - } - - return null; - } - ) - ); - }, - - /** - `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 Route from '@ember/routing/route'; - - export default Route.extend({ - model(params) { - return this.store.findAll('author'); - } - }); - ``` - - _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({ - data: { - id: 'first', - type: 'author' - } - }); - - // adapter#findAll resolves with - // [ - // { - // id: 'second', - // type: 'author' - // } - // ] - store.findAll('author', { reload: true }).then(function(authors) { - 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. - - ### 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: - - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - shouldReloadAll(store, snapshotsArray) { - return false; - }, - - shouldBackgroundReloadAll(store, snapshotsArray) { - return true; - } - }); - - // ... - - store.push({ - data: { - id: 'first', - type: 'author' - } - }); - - let allAuthors; - store.findAll('author').then(function(authors) { - authors.getEach('id'); // ['first'] - - allAuthors = authors; - }); - - // later, once adapter#findAll resolved with - // [ - // { - // id: 'second', - // type: 'author' - // } - // ] - - allAuthors.getEach('id'); // ['first', 'second'] - ``` - - 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 Route from '@ember/routing/route'; - - export default Route.extend({ - model() { - 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 Route from '@ember/routing/route'; - - export default Route.extend({ - model(params) { - return this.store.findAll('post', { - adapterOptions: { subscribe: false } - }); - } - }); - ``` - - ```app/adapters/post.js - import MyCustomAdapter from './custom-adapter'; - - export default MyCustomAdapter.extend({ - findAll(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. - - ### Retrieving Related Model Records - - If you use an adapter such as Ember's default - [`JSONAPIAdapter`](https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) - that supports the [JSON API specification](http://jsonapi.org/) and if your server - endpoint supports the use of an - ['include' query parameter](http://jsonapi.org/format/#fetching-includes), - you can use `findAll()` to automatically retrieve additional records related to - those requested by supplying an `include` parameter in the `options` object. - - For example, given a `post` model that has a `hasMany` relationship with a `comment` - model, when we retrieve all of the post records we can have the server also return - all of the posts' comments in the same request: - - ```app/routes/posts.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - model() { - return this.store.findAll('post', { include: 'comments' }); - } - }); - - ``` - Multiple relationships can be requested using an `include` parameter consisting of a - comma-separated list (without white-space) while nested relationships can be specified - using a dot-separated sequence of relationship names. So to request both the posts' - comments and the authors of those comments the request would look like this: - - ```app/routes/posts.js - import Route from '@ember/routing/route'; - - export default Route.extend({ - model() { - return this.store.findAll('post', { include: 'comments,comments.author' }); - } - }); - - ``` - - See [query](#method_query) to only get a subset of records from the server. - - @since 1.13.0 - @method findAll - @param {String} modelName - @param {Object} options - @return {Promise} promise - */ - findAll(modelName, options) { - if (DEBUG) { - assertDestroyingStore(this, 'findAll'); - } - assert(`You need to pass a model name to the store's findAll method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let token = heimdall.start('store.findAll'); - let normalizedModelName = normalizeModelName(modelName); - let fetch = this._fetchAll(normalizedModelName, this.peekAll(normalizedModelName), options); - - instrument(() => { - fetch.finally(() => { - heimdall.stop(token); - }); - }); - - return fetch; - }, - - /** - @method _fetchAll - @private - @param {DS.Model} modelName - @param {DS.RecordArray} array - @return {Promise} promise - */ - _fetchAll(modelName, array, options = {}) { - let adapter = this.adapterFor(modelName); - let sinceToken = this._internalModelsFor(modelName).metadata.since; - - assert(`You tried to load all records but you have no adapter (for ${modelName})`, adapter); - assert( - `You tried to load all records but your adapter does not implement 'findAll'`, - typeof adapter.findAll === 'function' - ); - - if (options.reload) { - set(array, 'isUpdating', true); - return promiseArray(_findAll(adapter, this, modelName, sinceToken, options)); - } - - let snapshotArray = array._createSnapshot(options); - - if (adapter.shouldReloadAll(this, snapshotArray)) { - set(array, 'isUpdating', true); - return promiseArray(_findAll(adapter, this, modelName, sinceToken, options)); - } - - if (options.backgroundReload === false) { - return promiseArray(Promise.resolve(array)); - } - - if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { - set(array, 'isUpdating', true); - _findAll(adapter, this, modelName, sinceToken, options); - } - - return promiseArray(Promise.resolve(array)); - }, - - /** - @method _didUpdateAll - @param {String} modelName - @private - */ - _didUpdateAll(modelName) { - heimdall.increment(_didUpdateAll); - this.recordArrayManager._didUpdateAll(modelName); - }, - - /** - This method returns a filtered array that contains all of the - known records for a given type in the store. - - Note that because it's just a filter, the result will contain any - locally created records of the type, however, it will not make a - request to the backend to retrieve additional records. If you - would like to request all the records from the backend please use - [store.findAll](#method_findAll). - - Also note that multiple calls to `peekAll` for a given type will always - return the same `RecordArray`. - - Example - - ```javascript - let localPosts = store.peekAll('post'); - ``` - - @since 1.13.0 - @method peekAll - @param {String} modelName - @return {DS.RecordArray} - */ - peekAll(modelName) { - if (DEBUG) { - assertDestroyingStore(this, 'peekAll'); - } - heimdall.increment(peekAll); - assert(`You need to pass a model name to the store's peekAll method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - return this.recordArrayManager.liveRecordArrayFor(normalizedModelName); - }, - - /** - This method unloads all records in the store. - It schedules unloading to happen during the next run loop. - - Optionally you can pass a type which unload all records for a given type. - - ```javascript - store.unloadAll(); - store.unloadAll('post'); - ``` - - @method unloadAll - @param {String} modelName - */ - unloadAll(modelName) { - if (DEBUG) { - assertDestroyedStoreOnly(this, 'unloadAll'); - } - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - !modelName || typeof modelName === 'string' - ); - - if (arguments.length === 0) { - this._identityMap.clear(); - } else { - let normalizedModelName = normalizeModelName(modelName); - this._internalModelsFor(normalizedModelName).clear(); - } - }, - - filter() { - assert( - 'The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', - false - ); - }, - - // .............. - // . PERSISTING . - // .............. - - /** - This method is called by `record.save`, and gets passed a - resolver for the promise that `record.save` returns. - - It schedules saving to happen at the end of the run loop. - - @method scheduleSave - @private - @param {InternalModel} internalModel - @param {Resolver} resolver - @param {Object} options - */ - scheduleSave(internalModel, resolver, options) { - let snapshot = internalModel.createSnapshot(options); - internalModel.flushChangedAttributes(); - internalModel.adapterWillCommit(); - this._pendingSave.push({ - snapshot: snapshot, - resolver: resolver, - }); - emberRun.scheduleOnce('actions', this, this.flushPendingSave); - }, - - /** - This method is called at the end of the run loop, and - flushes any records passed into `scheduleSave` - - @method flushPendingSave - @private - */ - flushPendingSave() { - let pending = this._pendingSave.slice(); - this._pendingSave = []; - - for (let i = 0, j = pending.length; i < j; i++) { - let pendingItem = pending[i]; - let snapshot = pendingItem.snapshot; - let resolver = pendingItem.resolver; - let internalModel = snapshot._internalModel; - let adapter = this.adapterFor(internalModel.modelName); - let operation; - - if (internalModel.currentState.stateName === 'root.deleted.saved') { - resolver.resolve(); - continue; - } else if (internalModel.isNew()) { - operation = 'createRecord'; - } else if (internalModel.isDeleted()) { - operation = 'deleteRecord'; - } else { - operation = 'updateRecord'; - } - - resolver.resolve(_commit(adapter, this, operation, snapshot)); - } - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is resolved. - - If the data provides a server-generated ID, it will - update the record and the store's indexes. - - @method didSaveRecord - @private - @param {InternalModel} internalModel the in-flight internal model - @param {Object} data optional data (see above) - */ - didSaveRecord(internalModel, dataArg) { - if (DEBUG) { - assertDestroyingStore(this, 'didSaveRecord'); - } - let data; - if (dataArg) { - data = dataArg.data; - } - if (data) { - // normalize relationship IDs into records - this.updateId(internalModel, data); - this._setupRelationshipsForModel(internalModel, data); - } else { - assert( - `Your ${ - internalModel.modelName - } record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.`, - internalModel.id - ); - } - - //We first make sure the primary data has been updated - //TODO try to move notification to the user to the end of the runloop - internalModel.adapterDidCommit(data); - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is rejected with a `DS.InvalidError`. - - @method recordWasInvalid - @private - @param {InternalModel} internalModel - @param {Object} errors - */ - recordWasInvalid(internalModel, errors) { - if (DEBUG) { - assertDestroyingStore(this, 'recordWasInvalid'); - } - internalModel.adapterDidInvalidate(errors); - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is rejected (with anything other than a `DS.InvalidError`). - - @method recordWasError - @private - @param {InternalModel} internalModel - @param {Error} error - */ - recordWasError(internalModel, error) { - if (DEBUG) { - assertDestroyingStore(this, 'recordWasError'); - } - internalModel.adapterDidError(error); - }, - - /** - When an adapter's `createRecord`, `updateRecord` or `deleteRecord` - resolves with data, this method extracts the ID from the supplied - data. - - @method updateId - @private - @param {InternalModel} internalModel - @param {Object} data - */ - updateId(internalModel, data) { - if (DEBUG) { - assertDestroyingStore(this, 'updateId'); - } - let oldId = internalModel.id; - let modelName = internalModel.modelName; - let id = coerceId(data.id); - - // ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record) - assert( - `'${modelName}' was saved to the server, but the response does not have an id and your record does not either.`, - !(id === null && oldId === null) - ); - - // ID absolutely can't be different than oldID if oldID is not null - assert( - `'${modelName}:${oldId}' was saved to the server, but the response returned the new id '${id}'. The store cannot assign a new id to a record that already has an id.`, - !(oldId !== null && id !== oldId) - ); - - // ID can be null if oldID is not null (altered ID in response for a record) - // however, this is more than likely a developer error. - if (oldId !== null && id === null) { - warn( - `Your ${modelName} record was saved to the server, but the response does not have an id.`, - !(oldId !== null && id === null) - ); - return; - } - - let existingInternalModel = this._existingInternalModelForId(modelName, id); - - assert( - `'${modelName}' was saved to the server, but the response returned the new id '${id}', which has already been used with another record.'`, - isNone(existingInternalModel) || existingInternalModel === internalModel - ); - - this._internalModelsFor(internalModel.modelName).set(id, internalModel); - - internalModel.setId(id); - }, - - /** - Returns a map of IDs to client IDs for a given modelName. - - @method _internalModelsFor - @private - @param {String} modelName - @return {Object} recordMap - */ - _internalModelsFor(modelName) { - heimdall.increment(_internalModelsFor); - return this._identityMap.retrieve(modelName); - }, - - // ................ - // . LOADING DATA . - // ................ - - /** - This internal method is used by `push`. - - @method _load - @private - @param {Object} data - */ - _load(data) { - heimdall.increment(_load); - let modelName = normalizeModelName(data.type); - let internalModel = this._internalModelForId(modelName, data.id); - - let isUpdate = internalModel.currentState.isEmpty === false; - - internalModel.setupData(data); - - if (isUpdate) { - this.recordArrayManager.recordDidChange(internalModel); - } else { - this.recordArrayManager.recordWasLoaded(internalModel); - } - - return internalModel; - }, - - /* - @deprecated - @private - */ - _modelForMixin(modelName) { - deprecate( - '_modelForMixin is private and deprecated and should never be used directly, use modelFor instead', - false, - { - id: 'ember-data:_modelForMixin', - until: '3.5', - } - ); - assert( - `You need to pass a model name to the store's _modelForMixin method`, - isPresent(modelName) - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - - return _modelForMixin(this, normalizedModelName); - }, - - /** - Returns the model class for the particular `modelName`. - - The class of a model might be useful if you want to get a list of all the - relationship names of the model, see - [`relationshipNames`](https://emberjs.com/api/data/classes/DS.Model.html#property_relationshipNames) - for example. - - @method modelFor - @param {String} modelName - @return {DS.Model} - */ - modelFor(modelName) { - if (DEBUG) { - assertDestroyedStoreOnly(this, 'modelFor'); - } - assert(`You need to pass a model name to the store's modelFor method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - - let maybeFactory = this._modelFactoryFor(modelName); - - // for factorFor factory/class split - return maybeFactory.class ? maybeFactory.class : maybeFactory; - }, - - /* - @deprecated - @private - */ - _modelFor(modelName) { - deprecate('_modelFor is private and deprecated, you should use modelFor instead', false, { - id: 'ember-data:_modelFor', - until: '3.5', - }); - return this.modelFor(modelName); - }, - - _modelFactoryFor(modelName) { - if (DEBUG) { - assertDestroyedStoreOnly(this, '_modelFactoryFor'); - } - assert( - `You need to pass a model name to the store's _modelFactoryFor method`, - isPresent(modelName) - ); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - let factory = getModelFactory(this, this._modelFactoryCache, normalizedModelName); - - if (factory === null) { - throw new EmberError(`No model was found for '${normalizedModelName}'`); - } - - return factory; - }, - - /* - @deprecated - @private - */ - modelFactoryFor(modelName) { - deprecate('modelFactoryFor is private and deprecated', false, { - id: 'ember-data:modelFactoryFor', - until: '3.5', - }); - return this._modelFactoryFor(modelName); - }, - - /* - Returns whether a ModelClass exists for a given modelName - This exists for legacy support for the RESTSerializer, - which due to how it must guess whether a key is a model - must query for whether a match exists. - - We should investigate an RFC to make this public or removing - this requirement. - - @private - */ - _hasModelFor(modelName) { - if (DEBUG) { - assertDestroyingStore(this, '_hasModelFor'); - } - assert(`You need to pass a model name to the store's hasModelFor method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - let factory = getModelFactory(this, this._modelFactoryCache, normalizedModelName); - - return factory !== null; - }, - - /** - Push some data for a given type into the store. - - This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - - record's `type` should always be in singular, dasherized form - - members (properties) should be camelCased - - [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): - - ```js - store.push({ - data: { - // primary data for single record of type `Person` - id: '1', - type: 'person', - attributes: { - firstName: 'Daniel', - lastName: 'Kmak' - } - } - }); - ``` - - [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) - - `data` property can also hold an array (of records): - - ```js - store.push({ - data: [ - // an array of records - { - id: '1', - type: 'person', - attributes: { - firstName: 'Daniel', - lastName: 'Kmak' - } - }, - { - id: '2', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - } - } - ] - }); - ``` - - [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) - - There are some typical properties for `JSONAPI` payload: - * `id` - mandatory, unique record's key - * `type` - mandatory string which matches `model`'s dasherized name in singular form - * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model - * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - - [`links`](http://jsonapi.org/format/#document-links) - - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship - - For this model: - - ```app/models/person.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - - children: DS.hasMany('person') - }); - ``` - - To represent the children as IDs: - - ```js - { - data: { - id: '1', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - }, - relationships: { - children: { - data: [ - { - id: '2', - type: 'person' - }, - { - id: '3', - type: 'person' - }, - { - id: '4', - type: 'person' - } - ] - } - } - } - } - ``` - - [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) - - To represent the children relationship as a URL: - - ```js - { - data: { - id: '1', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - }, - relationships: { - children: { - links: { - related: '/people/1/children' - } - } - } - } - } - ``` - - If you're streaming data or implementing an adapter, make sure - that you have converted the incoming data into this form. The - store's [normalize](#method_normalize) method is a convenience - helper for converting a json payload into the form Ember Data - expects. - - ```js - store.push(store.normalize('person', data)); - ``` - - This method can be used both to push in brand new - records, as well as to update existing records. - - @method push - @param {Object} data - @return {DS.Model|Array} the record(s) that was created or - updated. - */ - push(data) { - if (DEBUG) { - assertDestroyingStore(this, 'push'); - } - let token = heimdall.start('store.push'); - let pushed = this._push(data); - - if (Array.isArray(pushed)) { - let records = pushed.map(internalModel => internalModel.getRecord()); - heimdall.stop(token); - return records; - } - - if (pushed === null) { - heimdall.stop(token); - return null; - } - - let record = pushed.getRecord(); - heimdall.stop(token); - return record; - }, - - /* - Push some data in the form of a json-api document into the store, - without creating materialized records. - - @method _push - @private - @param {Object} jsonApiDoc - @return {DS.InternalModel|Array} pushed InternalModel(s) - */ - _push(jsonApiDoc) { - if (DEBUG) { - assertDestroyingStore(this, '_push'); - } - let token = heimdall.start('store._push'); - let internalModelOrModels = this._backburner.join(() => { - let included = jsonApiDoc.included; - let i, length; - - if (included) { - for (i = 0, length = included.length; i < length; i++) { - this._pushInternalModel(included[i]); - } - } - - if (Array.isArray(jsonApiDoc.data)) { - length = jsonApiDoc.data.length; - let internalModels = new Array(length); - - for (i = 0; i < length; i++) { - internalModels[i] = this._pushInternalModel(jsonApiDoc.data[i]); - } - return internalModels; - } - - if (jsonApiDoc.data === null) { - return null; - } - - assert( - `Expected an object in the 'data' property in a call to 'push' for ${ - jsonApiDoc.type - }, but was ${typeOf(jsonApiDoc.data)}`, - typeOf(jsonApiDoc.data) === 'object' - ); - - return this._pushInternalModel(jsonApiDoc.data); - }); - heimdall.stop(token); - return internalModelOrModels; - }, - - _pushInternalModel(data) { - heimdall.increment(_pushInternalModel); - let modelName = data.type; - assert( - `You must include an 'id' for ${modelName} in an object passed to 'push'`, - data.id !== null && data.id !== undefined && data.id !== '' - ); - assert( - `You tried to push data with a type '${modelName}' but no model could be found with that name.`, - this._hasModelFor(modelName) - ); - - if (DEBUG) { - // If ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload - // contains unknown attributes or relationships, log a warning. - - if (ENV.DS_WARN_ON_UNKNOWN_KEYS) { - let modelClass = this.modelFor(modelName); - - // Check unknown attributes - let unknownAttributes = Object.keys(data.attributes || {}).filter(key => { - return !get(modelClass, 'fields').has(key); - }); - let unknownAttributesMessage = `The payload for '${modelName}' contains these unknown attributes: ${unknownAttributes}. Make sure they've been defined in your model.`; - warn(unknownAttributesMessage, unknownAttributes.length === 0, { - id: 'ds.store.unknown-keys-in-payload', - }); - - // Check unknown relationships - let unknownRelationships = Object.keys(data.relationships || {}).filter(key => { - return !get(modelClass, 'fields').has(key); - }); - let unknownRelationshipsMessage = `The payload for '${modelName}' contains these unknown relationships: ${unknownRelationships}. Make sure they've been defined in your model.`; - warn(unknownRelationshipsMessage, unknownRelationships.length === 0, { - id: 'ds.store.unknown-keys-in-payload', - }); - } - } - - // Actually load the record into the store. - let internalModel = this._load(data); - - this._setupRelationshipsForModel(internalModel, data); - - return internalModel; - }, - - _setupRelationshipsForModel(internalModel, data) { - if (data.relationships === undefined) { - return; - } - - if (this._pushedInternalModels.push(internalModel, data) !== 2) { - return; - } - - this._backburner.schedule('normalizeRelationships', this, this._setupRelationships); - }, - - _setupRelationships() { - heimdall.increment(_setupRelationships); - let setupToken = heimdall.start('store._setupRelationships'); - let pushed = this._pushedInternalModels; - - // Cache the inverse maps for each modelClass that we visit during this - // payload push. In the common case where we are pushing many more - // instances than types we want to minimize the cost of looking up the - // inverse map and the overhead of Ember.get adds up. - let modelNameToInverseMap; - - for (let i = 0, l = pushed.length; i < l; i += 2) { - modelNameToInverseMap = modelNameToInverseMap || Object.create(null); - // This will convert relationships specified as IDs into DS.Model instances - // (possibly unloaded) and also create the data structures used to track - // relationships. - let internalModel = pushed[i]; - let data = pushed[i + 1]; - setupRelationships(this, internalModel, data, modelNameToInverseMap); - } - - pushed.length = 0; - heimdall.stop(setupToken); - }, - - /** - Push some raw data into the store. - - This method can be used both to push in brand new - records, as well as to update existing records. You - can push in more than one type of object at once. - All objects should be in the format expected by the - serializer. - - ```app/serializers/application.js - import DS from 'ember-data'; - - export default DS.ActiveModelSerializer; - ``` - - ```js - let pushData = { - posts: [ - { id: 1, post_title: "Great post", comment_ids: [2] } - ], - comments: [ - { id: 2, comment_body: "Insightful comment" } - ] - } - - store.pushPayload(pushData); - ``` - - By default, the data will be deserialized using a default - serializer (the application serializer if it exists). - - Alternatively, `pushPayload` will accept a model type which - will determine which serializer will process the payload. - - ```app/serializers/application.js - import DS from 'ember-data'; - - export default DS.ActiveModelSerializer; - ``` - - ```app/serializers/post.js - import DS from 'ember-data'; - - export default DS.JSONSerializer; - ``` - - ```js - store.pushPayload(pushData); // Will use the application serializer - store.pushPayload('post', pushData); // Will use the post serializer - ``` - - @method pushPayload - @param {String} modelName Optionally, a model type used to determine which serializer will be used - @param {Object} inputPayload - */ - pushPayload(modelName, inputPayload) { - if (DEBUG) { - assertDestroyingStore(this, 'pushPayload'); - } - let serializer; - let payload; - if (!inputPayload) { - payload = modelName; - serializer = this.serializerFor('application'); - assert( - `You cannot use 'store#pushPayload' without a modelName unless your default serializer defines 'pushPayload'`, - typeof serializer.pushPayload === 'function' - ); - } else { - payload = inputPayload; - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - serializer = this.serializerFor(normalizedModelName); - } - serializer.pushPayload(this, payload); - }, - - /** - `normalize` converts a json payload into the normalized form that - [push](#method_push) expects. - - Example - - ```js - socket.on('message', function(message) { - let modelName = message.model; - let data = message.data; - store.push(store.normalize(modelName, data)); - }); - ``` - - @method normalize - @param {String} modelName The name of the model type for this payload - @param {Object} payload - @return {Object} The normalized payload - */ - normalize(modelName, payload) { - if (DEBUG) { - assertDestroyingStore(this, 'normalize'); - } - heimdall.increment(normalize); - assert(`You need to pass a model name to the store's normalize method`, isPresent(modelName)); - assert( - `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${inspect( - modelName - )}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - let serializer = this.serializerFor(normalizedModelName); - let model = this.modelFor(normalizedModelName); - return serializer.normalize(model, payload); - }, - - /** - Build a brand new record for a given type, ID, and - initial data. - - @method _buildInternalModel - @private - @param {String} modelName - @param {String} id - @param {Object} data - @return {InternalModel} internal model - */ - _buildInternalModel(modelName, id, data) { - heimdall.increment(_buildInternalModel); - - assert( - `You can no longer pass a modelClass as the first argument to store._buildInternalModel. Pass modelName instead.`, - typeof modelName === 'string' - ); - - let existingInternalModel = this._existingInternalModelForId(modelName, id); - - assert( - `The id ${id} has already been used with another record for modelClass '${modelName}'.`, - !existingInternalModel - ); - - // lookupFactory should really return an object that creates - // instances with the injections applied - let internalModel = new InternalModel(modelName, id, this, data); - - this._internalModelsFor(modelName).add(internalModel, id); - - return internalModel; - }, - - _existingInternalModelForId(modelName, id) { - let internalModel = this._internalModelsFor(modelName).get(id); - - if (internalModel && internalModel.hasScheduledDestroy()) { - // unloadRecord is async, if one attempts to unload + then sync create, - // we must ensure the unload is complete before starting the create - // The push path will take _internalModelForId() - // which will call `cancelDestroy` instead for this unload + then - // sync push scenario. Once we have true client-side - // delete signaling, we should never call destroySync - internalModel.destroySync(); - internalModel = null; - } - return internalModel; - }, - - //Called by the state machine to notify the store that the record is ready to be interacted with - recordWasLoaded(record) { - if (DEBUG) { - assertDestroyingStore(this, 'recordWasLoaded'); - } - this.recordArrayManager.recordWasLoaded(record); - }, - - // ............... - // . DESTRUCTION . - // ............... - - /** - When a record is destroyed, this un-indexes it and - removes it from any record arrays so it can be GCed. - - @method _removeFromIdMap - @private - @param {InternalModel} internalModel - */ - _removeFromIdMap(internalModel) { - let recordMap = this._internalModelsFor(internalModel.modelName); - let id = internalModel.id; - - recordMap.remove(internalModel, id); - }, - - // ...................... - // . PER-TYPE ADAPTERS - // ...................... - - /** - Returns an instance of the adapter for a given type. For - example, `adapterFor('person')` will return an instance of - `App.PersonAdapter`. - - If no `App.PersonAdapter` is found, this method will look - for an `App.ApplicationAdapter` (the default adapter for - your entire application). - - If no `App.ApplicationAdapter` is found, it will return - the value of the `defaultAdapter`. - - @method adapterFor - @public - @param {String} modelName - @return DS.Adapter - */ - adapterFor(modelName) { - if (DEBUG) { - assertDestroyingStore(this, 'adapterFor'); - } - heimdall.increment(adapterFor); - assert(`You need to pass a model name to the store's adapterFor method`, isPresent(modelName)); - assert( - `Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - - let { _adapterCache } = this; - let adapter = _adapterCache[normalizedModelName]; - if (adapter) { - return adapter; - } - - let owner = getOwner(this); - - adapter = owner.lookup(`adapter:${normalizedModelName}`); - if (adapter !== undefined) { - set(adapter, 'store', this); - _adapterCache[normalizedModelName] = adapter; - return adapter; - } - - // no adapter found for the specific model, fallback and check for application adapter - adapter = _adapterCache.application || owner.lookup('adapter:application'); - if (adapter !== undefined) { - set(adapter, 'store', this); - _adapterCache[normalizedModelName] = adapter; - _adapterCache.application = adapter; - return adapter; - } - - // no model specific adapter or application adapter, check for an `adapter` - // property defined on the store - let adapterName = this.get('adapter'); - adapter = _adapterCache[adapterName] || owner.lookup(`adapter:${adapterName}`); - if (adapter !== undefined) { - set(adapter, 'store', this); - _adapterCache[normalizedModelName] = adapter; - _adapterCache[adapterName] = adapter; - return adapter; - } - - // final fallback, no model specific adapter, no application adapter, no - // `adapter` property on store: use json-api adapter - adapter = _adapterCache['-json-api'] || owner.lookup('adapter:-json-api'); - set(adapter, 'store', this); - _adapterCache[normalizedModelName] = adapter; - _adapterCache['-json-api'] = adapter; - return adapter; - }, - - // .............................. - // . RECORD CHANGE NOTIFICATION . - // .............................. - - /** - Returns an instance of the serializer for a given type. For - example, `serializerFor('person')` will return an instance of - `App.PersonSerializer`. - - If no `App.PersonSerializer` is found, this method will look - for an `App.ApplicationSerializer` (the default serializer for - your entire application). - - if no `App.ApplicationSerializer` is found, it will attempt - to get the `defaultSerializer` from the `PersonAdapter` - (`adapterFor('person')`). - - If a serializer cannot be found on the adapter, it will fall back - to an instance of `DS.JSONSerializer`. - - @method serializerFor - @public - @param {String} modelName the record to serialize - @return {DS.Serializer} - */ - serializerFor(modelName) { - if (DEBUG) { - assertDestroyingStore(this, 'serializerFor'); - } - heimdall.increment(serializerFor); - assert( - `You need to pass a model name to the store's serializerFor method`, - isPresent(modelName) - ); - assert( - `Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ${modelName}`, - typeof modelName === 'string' - ); - let normalizedModelName = normalizeModelName(modelName); - - let { _serializerCache } = this; - let serializer = _serializerCache[normalizedModelName]; - if (serializer) { - return serializer; - } - - let owner = getOwner(this); - - serializer = owner.lookup(`serializer:${normalizedModelName}`); - if (serializer !== undefined) { - set(serializer, 'store', this); - _serializerCache[normalizedModelName] = serializer; - return serializer; - } - - // no serializer found for the specific model, fallback and check for application serializer - serializer = _serializerCache.application || owner.lookup('serializer:application'); - if (serializer !== undefined) { - set(serializer, 'store', this); - _serializerCache[normalizedModelName] = serializer; - _serializerCache.application = serializer; - return serializer; - } - - // no model specific serializer or application serializer, check for the `defaultSerializer` - // property defined on the adapter - let adapter = this.adapterFor(modelName); - let serializerName = get(adapter, 'defaultSerializer'); - serializer = _serializerCache[serializerName] || owner.lookup(`serializer:${serializerName}`); - if (serializer !== undefined) { - set(serializer, 'store', this); - _serializerCache[normalizedModelName] = serializer; - _serializerCache[serializerName] = serializer; - return serializer; - } - - // final fallback, no model specific serializer, no application serializer, no - // `serializer` property on store: use json-api serializer - serializer = _serializerCache['-default'] || owner.lookup('serializer:-default'); - set(serializer, 'store', this); - _serializerCache[normalizedModelName] = serializer; - _serializerCache['-default'] = serializer; - - return serializer; - }, - - willDestroy() { - this._super(...arguments); - this._pushedInternalModels = null; - this.recordArrayManager.destroy(); - - this._relationshipsPayloads = null; - this._adapterCache = null; - this._serializerCache = null; - - this.unloadAll(); - - if (DEBUG) { - unregisterWaiter(this.__asyncWaiter); - let shouldTrack = this.shouldTrackAsyncRequests; - let tracked = this._trackedAsyncRequests; - let isSettled = tracked.length === 0; - - if (!isSettled) { - if (shouldTrack) { - throw new Error( - 'Async Request leaks detected. Add a breakpoint here and set `store.generateStackTracesForTrackedRequests = true;`to inspect traces for leak origins:\n\t - ' + - tracked.map(o => o.label).join('\n\t - ') - ); - } else { - warn( - 'Async Request leaks detected. Add a breakpoint here and set `store.generateStackTracesForTrackedRequests = true;`to inspect traces for leak origins:\n\t - ' + - tracked.map(o => o.label).join('\n\t - '), - false, - { - id: 'ds.async.leak.detected', - } - ); - } - } - } - }, - - _updateRelationshipState(relationship) { - if (this._updatedRelationships.push(relationship) !== 1) { - return; - } - - this._backburner.join(() => { - this._backburner.schedule('syncRelationships', this, this._flushUpdatedRelationships); - }); - }, - - _flushUpdatedRelationships() { - let updated = this._updatedRelationships; - - for (let i = 0, l = updated.length; i < l; i++) { - updated[i].flushCanonical(); - } - - updated.length = 0; - }, - - _updateInternalModel(internalModel) { - if (this._updatedInternalModels.push(internalModel) !== 1) { - return; - } - - emberRun.schedule('actions', this, this._flushUpdatedInternalModels); - }, - - _flushUpdatedInternalModels() { - let updated = this._updatedInternalModels; - - for (let i = 0, l = updated.length; i < l; i++) { - updated[i]._triggerDeferredTriggers(); - } - - updated.length = 0; - }, - - _pushResourceIdentifier(relationship, resourceIdentifier) { - if (isNone(resourceIdentifier)) { - return; - } - if (DEBUG) { - assertRelationshipData( - this, - relationship.internalModel, - resourceIdentifier, - relationship.relationshipMeta - ); - } - - return this._internalModelForId(resourceIdentifier.type, resourceIdentifier.id); - }, - - _pushResourceIdentifiers(relationship, resourceIdentifiers) { - if (isNone(resourceIdentifiers)) { - return; - } - - assert( - `A ${ - relationship.internalModel.modelName - } record was pushed into the store with the value of ${relationship.key} being '${inspect( - resourceIdentifiers - )}', but ${ - relationship.key - } is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.`, - Array.isArray(resourceIdentifiers) - ); - - let _internalModels = new Array(resourceIdentifiers.length); - for (let i = 0; i < resourceIdentifiers.length; i++) { - _internalModels[i] = this._pushResourceIdentifier(relationship, resourceIdentifiers[i]); - } - return _internalModels; - }, -}); - -function _commit(adapter, store, operation, snapshot) { - let internalModel = snapshot._internalModel; - let modelName = snapshot.modelName; - let modelClass = store.modelFor(modelName); - assert(`You tried to update a record but you have no adapter (for ${modelName})`, adapter); - assert( - `You tried to update a record but your adapter (for ${modelName}) does not implement '${operation}'`, - typeof adapter[operation] === 'function' - ); - - let promise = Promise.resolve().then(() => adapter[operation](store, modelClass, snapshot)); - let serializer = serializerForAdapter(store, adapter, modelName); - let label = `DS: Extract and notify about ${operation} completion of ${internalModel}`; - - assert( - `Your adapter's '${operation}' method must return a value, but it returned 'undefined'`, - promise !== undefined - ); - - promise = guardDestroyedStore(promise, store, label); - promise = _guard(promise, _bind(_objectIsAlive, internalModel)); - - return promise.then( - adapterPayload => { - /* - Note to future spelunkers hoping to optimize. - We rely on this `run` to create a run loop if needed - that `store._push` and `store.didSaveRecord` will both share. - - We use `join` because it is often the case that we - have an outer run loop available still from the first - call to `store._push`; - */ - store._backburner.join(() => { - let payload, data; - if (adapterPayload) { - payload = normalizeResponseHelper( - serializer, - store, - modelClass, - adapterPayload, - snapshot.id, - operation - ); - if (payload.included) { - store._push({ data: null, included: payload.included }); - } - data = payload.data; - } - store.didSaveRecord(internalModel, { data }); - }); - - return internalModel; - }, - function(error) { - if (error instanceof InvalidError) { - let errors = serializer.extractErrors(store, modelClass, error, snapshot.id); - - store.recordWasInvalid(internalModel, errors); - } else { - store.recordWasError(internalModel, error); - } - - throw error; - }, - label - ); -} - -function isInverseRelationshipInitialized(store, internalModel, data, key, modelNameToInverseMap) { - let relationshipData = data.relationships[key].data; - - if (!relationshipData) { - // can't check inverse for eg { comments: { links: { related: URL }}} - return false; - } - - let inverseMap = modelNameToInverseMap[internalModel.modelName]; - if (!inverseMap) { - inverseMap = modelNameToInverseMap[internalModel.modelName] = get( - internalModel.type, - 'inverseMap' - ); - } - let inverseRelationshipMetadata = inverseMap[key]; - if (inverseRelationshipMetadata === undefined) { - inverseRelationshipMetadata = internalModel.type.inverseFor(key, store); - } - - if (!inverseRelationshipMetadata) { - return false; - } - - let { name: inverseRelationshipName } = inverseRelationshipMetadata; - - if (Array.isArray(relationshipData)) { - for (let i = 0; i < relationshipData.length; ++i) { - let inverseInternalModel = store - ._internalModelsFor(relationshipData[i].type) - .get(relationshipData[i].id); - if ( - inverseInternalModel && - inverseInternalModel._relationships.has(inverseRelationshipName) - ) { - return true; - } - } - - return false; - } else { - let inverseInternalModel = store - ._internalModelsFor(relationshipData.type) - .get(relationshipData.id); - return inverseInternalModel && inverseInternalModel._relationships.has(inverseRelationshipName); - } -} - -/** - * @function - * @param store - * @param cache modelFactoryCache - * @param normalizedModelName already normalized modelName - * @return {*} - */ -function getModelFactory(store, cache, normalizedModelName) { - let factory = cache[normalizedModelName]; - - if (!factory) { - factory = _lookupModelFactory(store, normalizedModelName); - - if (!factory) { - //Support looking up mixins as base types for polymorphic relationships - factory = _modelForMixin(store, normalizedModelName); - } - - if (!factory) { - // we don't cache misses in case someone wants to register a missing model - return null; - } - - // interopt with the future - let klass = getOwner(store).factoryFor ? factory.class : factory; - assert(`'${inspect(klass)}' does not appear to be an ember-data model`, klass.isModel); - - // TODO: deprecate this - let hasOwnModelNameSet = klass.modelName && klass.hasOwnProperty('modelName'); - if (!hasOwnModelNameSet) { - klass.modelName = normalizedModelName; - } - - cache[normalizedModelName] = factory; - } - - return factory; -} - -function _lookupModelFactory(store, normalizedModelName) { - let owner = getOwner(store); - - if (owner.factoryFor) { - return owner.factoryFor(`model:${normalizedModelName}`); - } else { - return owner._lookupFactory(`model:${normalizedModelName}`); - } -} - -/* - In case someone defined a relationship to a mixin, for example: - ``` - let Comment = DS.Model.extend({ - owner: belongsTo('commentable'. { polymorphic: true }) - }); - let Commentable = Ember.Mixin.create({ - comments: hasMany('comment') - }); - ``` - we want to look up a Commentable class which has all the necessary - relationship metadata. Thus, we look up the mixin and create a mock - DS.Model, so we can access the relationship CPs of the mixin (`comments`) - in this case -*/ -function _modelForMixin(store, normalizedModelName) { - // container.registry = 2.1 - // container._registry = 1.11 - 2.0 - // container = < 1.11 - let owner = getOwner(store); - let mixin; - - if (owner.factoryFor) { - let MaybeMixin = owner.factoryFor(`mixin:${normalizedModelName}`); - mixin = MaybeMixin && MaybeMixin.class; - } else { - mixin = owner._lookupFactory(`mixin:${normalizedModelName}`); - } - - if (mixin) { - let ModelForMixin = Model.extend(mixin); - ModelForMixin.reopenClass({ - __isMixin: true, - __mixin: mixin, - }); - - //Cache the class as a model - owner.register('model:' + normalizedModelName, ModelForMixin); - } - - return _lookupModelFactory(store, normalizedModelName); -} - -function setupRelationships(store, internalModel, data, modelNameToInverseMap) { - Object.keys(data.relationships).forEach(relationshipName => { - let relationships = internalModel._relationships; - let relationshipRequiresNotification = - relationships.has(relationshipName) || - isInverseRelationshipInitialized( - store, - internalModel, - data, - relationshipName, - modelNameToInverseMap - ); - - if (relationshipRequiresNotification) { - let relationshipData = data.relationships[relationshipName]; - relationships.get(relationshipName).push(relationshipData, false); - } - - if (DEBUG) { - let relationshipMeta = get(internalModel.type, 'relationshipsByName').get(relationshipName); - let relationshipData = data.relationships[relationshipName]; - if (!relationshipData || !relationshipMeta) { - return; - } - - if (relationshipData.links) { - let isAsync = relationshipMeta.options && relationshipMeta.options.async !== false; - warn( - `You pushed a record of type '${ - internalModel.modelName - }' with a relationship '${relationshipName}' configured as 'async: false'. You've included a link but no primary data, this may be an error in your payload. EmberData will treat this relationship as known-to-be-empty.`, - isAsync || relationshipData.data, - { - id: 'ds.store.push-link-for-sync-relationship', - } - ); - } else if (relationshipData.data) { - if (relationshipMeta.kind === 'belongsTo') { - assertRelationshipData(store, internalModel, relationshipData.data, relationshipMeta); - } else if (relationshipMeta.kind === 'hasMany') { - assert( - `A ${ - internalModel.modelName - } record was pushed into the store with the value of ${relationshipName} being '${inspect( - relationshipData.data - )}', but ${relationshipName} is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.`, - Array.isArray(relationshipData.data) - ); - if (Array.isArray(relationshipData.data)) { - for (let i = 0; i < relationshipData.data.length; i++) { - assertRelationshipData( - store, - internalModel, - relationshipData.data[i], - relationshipMeta - ); - } - } - } - } - } - }); -} - -let assertRelationshipData; -let assertDestroyingStore; -let assertDestroyedStoreOnly; - -if (DEBUG) { - assertRelationshipData = function assertRelationshipData(store, internalModel, data, meta) { - assert( - `A ${internalModel.modelName} record was pushed into the store with the value of ${ - meta.key - } being '${JSON.stringify(data)}', but ${ - meta.key - } is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.`, - !Array.isArray(data) - ); - assert( - `Encountered a relationship identifier without a type for the ${meta.kind} relationship '${ - meta.key - }' on ${internalModel}, expected a json-api identifier with type '${ - meta.type - }' but found '${JSON.stringify( - data - )}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.`, - data === null || (typeof data.type === 'string' && data.type.length) - ); - assert( - `Encountered a relationship identifier without an id for the ${meta.kind} relationship '${ - meta.key - }' on ${internalModel}, expected a json-api identifier but found '${JSON.stringify( - data - )}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.`, - data === null || coerceId(data.id) - ); - assert( - `Encountered a relationship identifier with type '${data.type}' for the ${ - meta.kind - } relationship '${meta.key}' on ${internalModel}, Expected a json-api identifier with type '${ - meta.type - }'. No model was found for '${data.type}'.`, - data === null || !data.type || store._hasModelFor(data.type) - ); - }; - assertDestroyingStore = function assertDestroyedStore(store, method) { - if (!store.shouldAssertMethodCallsOnDestroyedStore) { - deprecate( - `Attempted to call store.${method}(), but the store instance has already been destroyed.`, - !(store.isDestroying || store.isDestroyed), - { - id: 'ember-data:method-calls-on-destroyed-store', - until: '3.8', - } - ); - } else { - assert( - `Attempted to call store.${method}(), but the store instance has already been destroyed.`, - !(store.isDestroying || store.isDestroyed) - ); - } - }; - assertDestroyedStoreOnly = function assertDestroyedStoreOnly(store, method) { - if (!store.shouldAssertMethodCallsOnDestroyedStore) { - deprecate( - `Attempted to call store.${method}(), but the store instance has already been destroyed.`, - !store.isDestroyed, - { - id: 'ember-data:method-calls-on-destroyed-store', - until: '3.8', - } - ); - } else { - assert( - `Attempted to call store.${method}(), but the store instance has already been destroyed.`, - !store.isDestroyed - ); - } - }; -} - -export default Store; diff --git a/addon/-record-data-private/attr.js b/addon/-private/attr.js similarity index 100% rename from addon/-record-data-private/attr.js rename to addon/-private/attr.js diff --git a/addon/-record-data-private/index.js b/addon/-private/index.js similarity index 100% rename from addon/-record-data-private/index.js rename to addon/-private/index.js diff --git a/addon/-record-data-private/system/many-array.js b/addon/-private/system/many-array.js similarity index 100% rename from addon/-record-data-private/system/many-array.js rename to addon/-private/system/many-array.js diff --git a/addon/-record-data-private/system/model/internal-model.js b/addon/-private/system/model/internal-model.js similarity index 100% rename from addon/-record-data-private/system/model/internal-model.js rename to addon/-private/system/model/internal-model.js diff --git a/addon/-record-data-private/system/model/model.js b/addon/-private/system/model/model.js similarity index 100% rename from addon/-record-data-private/system/model/model.js rename to addon/-private/system/model/model.js diff --git a/addon/-record-data-private/system/model/record-data.js b/addon/-private/system/model/record-data.js similarity index 100% rename from addon/-record-data-private/system/model/record-data.js rename to addon/-private/system/model/record-data.js diff --git a/addon/-record-data-private/system/model/states.js b/addon/-private/system/model/states.js similarity index 100% rename from addon/-record-data-private/system/model/states.js rename to addon/-private/system/model/states.js diff --git a/addon/-record-data-private/system/promise-proxies.js b/addon/-private/system/promise-proxies.js similarity index 100% rename from addon/-record-data-private/system/promise-proxies.js rename to addon/-private/system/promise-proxies.js diff --git a/addon/-record-data-private/system/references/belongs-to.js b/addon/-private/system/references/belongs-to.js similarity index 100% rename from addon/-record-data-private/system/references/belongs-to.js rename to addon/-private/system/references/belongs-to.js diff --git a/addon/-record-data-private/system/references/has-many.js b/addon/-private/system/references/has-many.js similarity index 100% rename from addon/-record-data-private/system/references/has-many.js rename to addon/-private/system/references/has-many.js diff --git a/addon/-record-data-private/system/references/reference.js b/addon/-private/system/references/reference.js similarity index 100% rename from addon/-record-data-private/system/references/reference.js rename to addon/-private/system/references/reference.js diff --git a/addon/-record-data-private/system/relationships/belongs-to.js b/addon/-private/system/relationships/belongs-to.js similarity index 100% rename from addon/-record-data-private/system/relationships/belongs-to.js rename to addon/-private/system/relationships/belongs-to.js diff --git a/addon/-record-data-private/system/relationships/ext.js b/addon/-private/system/relationships/ext.js similarity index 100% rename from addon/-record-data-private/system/relationships/ext.js rename to addon/-private/system/relationships/ext.js diff --git a/addon/-record-data-private/system/relationships/has-many.js b/addon/-private/system/relationships/has-many.js similarity index 100% rename from addon/-record-data-private/system/relationships/has-many.js rename to addon/-private/system/relationships/has-many.js diff --git a/addon/-record-data-private/system/relationships/state/belongs-to.js b/addon/-private/system/relationships/state/belongs-to.js similarity index 100% rename from addon/-record-data-private/system/relationships/state/belongs-to.js rename to addon/-private/system/relationships/state/belongs-to.js diff --git a/addon/-record-data-private/system/relationships/state/create.js b/addon/-private/system/relationships/state/create.js similarity index 100% rename from addon/-record-data-private/system/relationships/state/create.js rename to addon/-private/system/relationships/state/create.js diff --git a/addon/-record-data-private/system/relationships/state/has-many.js b/addon/-private/system/relationships/state/has-many.js similarity index 100% rename from addon/-record-data-private/system/relationships/state/has-many.js rename to addon/-private/system/relationships/state/has-many.js diff --git a/addon/-record-data-private/system/relationships/state/relationship.js b/addon/-private/system/relationships/state/relationship.js similarity index 100% rename from addon/-record-data-private/system/relationships/state/relationship.js rename to addon/-private/system/relationships/state/relationship.js diff --git a/addon/-record-data-private/system/snapshot.js b/addon/-private/system/snapshot.js similarity index 100% rename from addon/-record-data-private/system/snapshot.js rename to addon/-private/system/snapshot.js diff --git a/addon/-record-data-private/system/store.js b/addon/-private/system/store.js similarity index 100% rename from addon/-record-data-private/system/store.js rename to addon/-private/system/store.js diff --git a/addon/-record-data-private/system/store/record-data-wrapper.js b/addon/-private/system/store/record-data-wrapper.js similarity index 100% rename from addon/-record-data-private/system/store/record-data-wrapper.js rename to addon/-private/system/store/record-data-wrapper.js diff --git a/index.js b/index.js index 28139e2aa48..3d04de9be16 100644 --- a/index.js +++ b/index.js @@ -5,7 +5,7 @@ const Funnel = require('broccoli-funnel'); const Rollup = require('broccoli-rollup'); const merge = require('broccoli-merge-trees'); const version = require('./lib/version'); -const { isInstrumentedBuild, useRecordData } = require('./lib/cli-flags'); +const { isInstrumentedBuild } = require('./lib/cli-flags'); const BroccoliDebug = require('broccoli-debug'); const calculateCacheKeyForTree = require('calculate-cache-key-for-tree'); @@ -73,33 +73,13 @@ module.exports = { version(), // compile the VERSION into the build ]); - let corePrivate = new Funnel(tree, { + let withPrivate = new Funnel(tree, { include: ['-private/**'], }); - let withPrivate; - - if (useRecordData()) { - withPrivate = new Funnel(tree, { - srcDir: '-record-data-private', - destDir: '-private', - }); - } else { - withPrivate = new Funnel(tree, { - srcDir: '-legacy-private', - destDir: '-private', - }); - } - - // do not allow overwrite, conflicts should error - // overwrite: false is default, but we are being explicit here - // since this is very important - withPrivate = merge([corePrivate, withPrivate], { overwrite: false }); let withoutPrivate = new Funnel(treeWithVersion, { exclude: [ '-private', - '-record-data-private', - '-legacy-private', isProductionEnv() && !isInstrumentedBuild() ? '-debug' : false, ].filter(Boolean), diff --git a/lib/cli-flags.js b/lib/cli-flags.js index 71324ca4514..aaa8be2e8e0 100644 --- a/lib/cli-flags.js +++ b/lib/cli-flags.js @@ -4,23 +4,6 @@ function isInstrumentedBuild() { return process.argv.includes('--instrument'); } -function useRecordData() { - try { - let currentProjectName = require(`${process.cwd()}/package`); - if ( - currentProjectName === 'ember-data' && - process.argv.includes('--disable-record-data-rfc-build') - ) { - return false; - } - } catch (e) { - // swallow any errors for missing package.json in CWD. - } - - return true; -} - module.exports = { isInstrumentedBuild, - useRecordData, }; diff --git a/tests/dummy/config/environment.js b/tests/dummy/config/environment.js index 365fd179067..8f6ea148349 100644 --- a/tests/dummy/config/environment.js +++ b/tests/dummy/config/environment.js @@ -5,7 +5,6 @@ var path = require('path'); var featuresJsonPath = path.join(__dirname, '../../../config/features.json'); var featuresJson = fs.readFileSync(featuresJsonPath, { encoding: 'utf8' }); var featureFlags = JSON.parse(featuresJson); -let { useRecordData } = require('../../../lib/cli-flags'); module.exports = function(environment) { var ENV = { @@ -48,9 +47,5 @@ module.exports = function(environment) { ENV.APP.rootElement = '#ember-testing'; } - ENV.emberData = { - enableRecordDataRFCBuild: useRecordData(), - }; - return ENV; }; diff --git a/tests/helpers/test-in-debug.js b/tests/helpers/test-in-debug.js index 561b1d4cbae..a5bbdce0894 100644 --- a/tests/helpers/test-in-debug.js +++ b/tests/helpers/test-in-debug.js @@ -1,8 +1,5 @@ import { DEBUG } from '@glimmer/env'; import { test, skip } from 'qunit'; -import config from 'dummy/config/environment'; - -const IS_RECORD_DATA = config.emberData.enableRecordDataRFCBuild; export function testInDebug() { if (DEBUG) { @@ -15,17 +12,9 @@ export function testInDebug() { export default testInDebug; export function testRecordData() { - if (IS_RECORD_DATA) { - test(...arguments); - } else { - skip(...arguments); - } + test(...arguments); } export function skipRecordData() { - if (IS_RECORD_DATA) { - skip(...arguments); - } else { - test(...arguments); - } + skip(...arguments); } From b13a6eaf45c61bc2f454e5c76246b3092a3e5657 Mon Sep 17 00:00:00 2001 From: Chris Thoburn Date: Thu, 4 Oct 2018 15:58:15 -0700 Subject: [PATCH 2/3] cleanup test skipping --- .../relationships/belongs-to-test.js | 3 +- .../acceptance/relationships/has-many-test.js | 3 +- tests/helpers/test-in-debug.js | 12 +- tests/integration/records/unload-test.js | 114 +------------- .../relationships/belongs-to-test.js | 4 +- .../relationships/has-many-test.js | 3 +- .../inverse-relationship-load-test.js | 2 +- .../inverse-relationships-test.js | 142 +----------------- tests/unit/model-test.js | 59 +------- tests/unit/store/async-leak-test.js | 2 +- 10 files changed, 14 insertions(+), 330 deletions(-) diff --git a/tests/acceptance/relationships/belongs-to-test.js b/tests/acceptance/relationships/belongs-to-test.js index 5a705deaabc..07c734ea5b2 100644 --- a/tests/acceptance/relationships/belongs-to-test.js +++ b/tests/acceptance/relationships/belongs-to-test.js @@ -1,4 +1,4 @@ -import { module } from 'qunit'; +import { module, skip as test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import JSONAPIAdapter from 'ember-data/adapters/json-api'; import Model from 'ember-data/model'; @@ -9,7 +9,6 @@ import JSONAPISerializer from 'ember-data/serializers/json-api'; import Store from 'ember-data/store'; import { resolve, reject } from 'rsvp'; import { ServerError } from 'ember-data/adapters/errors'; -import { skipRecordData as test } from '../../helpers/test-in-debug'; import Ember from 'ember'; class Person extends Model { diff --git a/tests/acceptance/relationships/has-many-test.js b/tests/acceptance/relationships/has-many-test.js index 29ad420597a..8246239c0a7 100644 --- a/tests/acceptance/relationships/has-many-test.js +++ b/tests/acceptance/relationships/has-many-test.js @@ -1,4 +1,4 @@ -import { module } from 'qunit'; +import { module, skip as test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import JSONAPIAdapter from 'ember-data/adapters/json-api'; import Model from 'ember-data/model'; @@ -10,7 +10,6 @@ import Store from 'ember-data/store'; import { resolve, reject } from 'rsvp'; import { ServerError } from 'ember-data/adapters/errors'; import Ember from 'ember'; -import { skipRecordData as test } from '../../helpers/test-in-debug'; function domListToArray(domList) { return Array.prototype.slice.call(domList); diff --git a/tests/helpers/test-in-debug.js b/tests/helpers/test-in-debug.js index a5bbdce0894..949b64daac2 100644 --- a/tests/helpers/test-in-debug.js +++ b/tests/helpers/test-in-debug.js @@ -1,20 +1,10 @@ import { DEBUG } from '@glimmer/env'; import { test, skip } from 'qunit'; -export function testInDebug() { +export default function testInDebug() { if (DEBUG) { test(...arguments); } else { skip(...arguments); } } - -export default testInDebug; - -export function testRecordData() { - test(...arguments); -} - -export function skipRecordData() { - skip(...arguments); -} diff --git a/tests/integration/records/unload-test.js b/tests/integration/records/unload-test.js index 26b750bfd7a..153740d5517 100644 --- a/tests/integration/records/unload-test.js +++ b/tests/integration/records/unload-test.js @@ -6,7 +6,6 @@ import { run } from '@ember/runloop'; import { module, test } from 'qunit'; import DS from 'ember-data'; import setupStore from 'dummy/tests/helpers/store'; -import { testRecordData, skipRecordData } from 'dummy/tests/helpers/test-in-debug'; function idsFromOrderedSet(set) { return set.list.map(i => i.id); @@ -721,7 +720,7 @@ test('(regression) unloadRecord followed by push in the same run-loop', function ); }); -testRecordData('unloading a disconnected subgraph clears the relevant internal models', function( +test('unloading a disconnected subgraph clears the relevant internal models', function( assert ) { env.adapter.shouldBackgroundReloadRecord = () => false; @@ -834,117 +833,6 @@ testRecordData('unloading a disconnected subgraph clears the relevant internal m }); }); -skipRecordData('unloading a disconnected subgraph clears the relevant internal models', function( - assert -) { - env.adapter.shouldBackgroundReloadRecord = () => false; - - run(() => { - env.store.push({ - data: { - type: 'person', - id: '1', - attributes: { - name: 'Could be Anybody', - }, - relationships: { - boats: { - data: [{ type: 'boat', id: '1' }, { type: 'boat', id: '2' }], - }, - }, - }, - }); - }); - - run(() => { - env.store.push({ - data: { - type: 'boat', - id: '1', - attributes: { - name: 'Boaty McBoatface', - }, - relationships: { - person: { - data: { type: 'person', id: '1' }, - }, - }, - }, - }); - }); - - run(() => { - env.store.push({ - data: { - type: 'boat', - id: '2', - attributes: { - name: 'The jackson', - }, - relationships: { - person: { - data: { type: 'person', id: '1' }, - }, - }, - }, - }); - }); - - assert.equal( - env.store._internalModelsFor('person').models.length, - 1, - 'one person record is loaded' - ); - assert.equal( - env.store._internalModelsFor('boat').models.length, - 2, - 'two boat records are loaded' - ); - assert.equal(env.store.hasRecordForId('person', 1), true); - assert.equal(env.store.hasRecordForId('boat', 1), true); - assert.equal(env.store.hasRecordForId('boat', 2), true); - - let checkOrphanCalls = 0; - let cleanupOrphanCalls = 0; - - function countOrphanCalls(record) { - let internalModel = record._internalModel; - let origCheck = internalModel._checkForOrphanedInternalModels; - let origCleanup = internalModel._cleanupOrphanedInternalModels; - - internalModel._checkForOrphanedInternalModels = function() { - ++checkOrphanCalls; - return origCheck.apply(record._internalModel, arguments); - }; - - internalModel._cleanupOrphanedInternalModels = function() { - ++cleanupOrphanCalls; - return origCleanup.apply(internalModel, arguments); - }; - } - countOrphanCalls(env.store.peekRecord('person', 1)); - countOrphanCalls(env.store.peekRecord('boat', 1)); - countOrphanCalls(env.store.peekRecord('boat', 2)); - - // make sure relationships are initialized - return env.store - .peekRecord('person', 1) - .get('boats') - .then(() => { - run(() => { - env.store.peekRecord('person', 1).unloadRecord(); - env.store.peekRecord('boat', 1).unloadRecord(); - env.store.peekRecord('boat', 2).unloadRecord(); - }); - - assert.equal(env.store._internalModelsFor('person').models.length, 0); - assert.equal(env.store._internalModelsFor('boat').models.length, 0); - - assert.equal(checkOrphanCalls, 3, 'each internalModel checks for cleanup'); - assert.equal(cleanupOrphanCalls, 1, 'each model data tries to cleanup'); - }); -}); - test('Unloading a record twice only schedules destroy once', function(assert) { const store = env.store; let record; diff --git a/tests/integration/relationships/belongs-to-test.js b/tests/integration/relationships/belongs-to-test.js index 82caea6d374..939e9b47acb 100644 --- a/tests/integration/relationships/belongs-to-test.js +++ b/tests/integration/relationships/belongs-to-test.js @@ -9,7 +9,7 @@ import { setupTest } from 'ember-qunit'; import Store from 'ember-data/store'; import Model from 'ember-data/model'; import { attr, belongsTo } from '@ember-decorators/data'; -import testInDebug, { testRecordData } from 'dummy/tests/helpers/test-in-debug'; +import testInDebug from 'dummy/tests/helpers/test-in-debug'; import { setup as setupModelFactoryInjections, reset as resetModelFactoryInjection, @@ -1910,7 +1910,7 @@ test("belongsTo relationship with links doesn't trigger extra change notificatio assert.equal(count, 0); }); -testRecordData( +test( "belongsTo relationship doesn't trigger when model data doesn't support implicit relationship", function(assert) { class TestRecordData extends RecordData { diff --git a/tests/integration/relationships/has-many-test.js b/tests/integration/relationships/has-many-test.js index 86f00bffc7f..f2a2f73dd0f 100644 --- a/tests/integration/relationships/has-many-test.js +++ b/tests/integration/relationships/has-many-test.js @@ -12,7 +12,6 @@ import setupStore from 'dummy/tests/helpers/store'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import { module, test, skip } from 'qunit'; import DS from 'ember-data'; -import { skipRecordData } from '../../helpers/test-in-debug'; let env, store, User, Contact, Email, Phone, Message, Post, Comment; let Book, Chapter, Page; @@ -960,7 +959,7 @@ test('A hasMany relationship can be reloaded if it was fetched via ids', functio }); }); -skipRecordData( +skip( 'A hasMany relationship can be reloaded even if it failed at the first time', async function(assert) { assert.expect(6); diff --git a/tests/integration/relationships/inverse-relationship-load-test.js b/tests/integration/relationships/inverse-relationship-load-test.js index a4628d13cd6..45791d91175 100644 --- a/tests/integration/relationships/inverse-relationship-load-test.js +++ b/tests/integration/relationships/inverse-relationship-load-test.js @@ -6,7 +6,7 @@ import Store from 'ember-data/store'; import Model from 'ember-data/model'; import { resolve } from 'rsvp'; import { attr, belongsTo, hasMany } from '@ember-decorators/data'; -import { testInDebug } from '../../helpers/test-in-debug'; +import testInDebug from '../../helpers/test-in-debug'; module('inverse relationship load test', function(hooks) { let store; diff --git a/tests/integration/relationships/inverse-relationships-test.js b/tests/integration/relationships/inverse-relationships-test.js index f7d5e944bd6..1ffa0c46681 100644 --- a/tests/integration/relationships/inverse-relationships-test.js +++ b/tests/integration/relationships/inverse-relationships-test.js @@ -1,8 +1,7 @@ import { run } from '@ember/runloop'; import { createStore } from 'dummy/tests/helpers/store'; import setupStore from 'dummy/tests/helpers/store'; - -import { testInDebug, testRecordData, skipRecordData } from 'dummy/tests/helpers/test-in-debug'; +import testInDebug from 'dummy/tests/helpers/test-in-debug'; import { module, test } from 'qunit'; import DS from 'ember-data'; @@ -486,144 +485,7 @@ testInDebug("Inverse relationships that don't exist throw a nice error for a bel }, /We found no inverse relationships by the name of 'testPost' on the 'user' model/); }); -skipRecordData('inverseFor short-circuits when inverse is null', function(assert) { - assert.expect(4); - Post = DS.Model.extend({ - comments: DS.hasMany('comment', { async: false, inverse: null }), - }); - - Comment = DS.Model.extend({ - post: DS.belongsTo('post', { async: false, inverse: null }), - }); - - User = DS.Model.extend({ - messages: DS.hasMany('message', { async: false, inverse: 'user' }), - }); - - Message = DS.Model.extend({ - user: DS.belongsTo('user', { async: false, inverse: 'messages' }), - }); - - var env = setupStore({ post: Post, comment: Comment, user: User, message: Message }); - var store = env.store; - - Post._findInverseFor = function() { - assert.notOk(true, 'Post model _findInverseFor is not called'); - }; - - Comment._findInverseFor = function() { - assert.notOk(true, 'Comment model _findInverseFor is not called'); - }; - - Message._findInverseFor = function() { - assert.ok(true, 'Message model _findInverseFor is called'); - }; - - User._findInverseFor = function() { - assert.ok(true, 'User model _findInverseFor is called'); - }; - - run(function() { - store.push({ - data: { - id: '1', - type: 'post', - relationships: { - comments: { - data: [ - { - id: '1', - type: 'comment', - }, - { - id: '2', - type: 'comment', - }, - ], - }, - }, - }, - }); - store.push({ - data: [ - { - id: '1', - type: 'comment', - relationships: { - post: { - data: { - id: '1', - type: 'post', - }, - }, - }, - }, - { - id: '2', - type: 'comment', - relationships: { - post: { - data: { - id: '1', - type: 'post', - }, - }, - }, - }, - ], - }); - store.push({ - data: { - id: '1', - type: 'user', - relationships: { - messages: { - data: [ - { - id: '1', - type: 'message', - }, - { - id: '2', - type: 'message', - }, - ], - }, - }, - }, - }); - store.push({ - data: [ - { - id: '1', - type: 'message', - relationships: { - user: { - data: { - id: '1', - type: 'user', - }, - }, - }, - }, - { - id: '2', - type: 'message', - relationships: { - post: { - data: { - id: '1', - type: 'user', - }, - }, - }, - }, - ], - }); - }); -}); - -testRecordData('inverseFor is only called when inverse is not null', function(assert) { +test('inverseFor is only called when inverse is not null', function(assert) { assert.expect(2); Post = DS.Model.extend({ comments: DS.hasMany('comment', { async: false, inverse: null }), diff --git a/tests/unit/model-test.js b/tests/unit/model-test.js index a1c7d38b7a1..f73a1512204 100644 --- a/tests/unit/model-test.js +++ b/tests/unit/model-test.js @@ -5,7 +5,7 @@ import { run } from '@ember/runloop'; import { createStore } from 'dummy/tests/helpers/store'; import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; -import { testInDebug, testRecordData, skipRecordData } from 'dummy/tests/helpers/test-in-debug'; +import testInDebug from 'dummy/tests/helpers/test-in-debug'; import { module, test } from 'qunit'; import DS from 'ember-data'; import { getOwner } from 'ember-data/-private'; @@ -1528,7 +1528,7 @@ test('setting the id after model creation should correctly update the id', funct }); }); -testRecordData( +test( 'updating the id with store.setRecordId should correctly when the id property is watched', function(assert) { assert.expect(2); @@ -1555,33 +1555,7 @@ testRecordData( } ); -skipRecordData( - 'updating the id with store.updateId should correctly when the id property is watched', - function(assert) { - assert.expect(2); - - const Person = DS.Model.extend({ - name: DS.attr('string'), - idComputed: computed('id', function() {}), - }); - - let { store } = setupStore({ - person: Person, - }); - - run(() => { - let person = store.createRecord('person'); - person.get('idComputed'); - - assert.equal(person.get('id'), null, 'initial created model id should be null'); - - store.updateId(person._internalModel, { id: 'john' }); - assert.equal(person.id, 'john', 'new id should be correctly set.'); - }); - } -); - -testRecordData( +test( 'accessing the model id without the get function should work when id is watched', function(assert) { assert.expect(2); @@ -1608,33 +1582,6 @@ testRecordData( } ); -skipRecordData( - 'accessing the model id without the get function should work when id is watched', - function(assert) { - assert.expect(2); - - const Person = DS.Model.extend({ - name: DS.attr('string'), - idComputed: computed('id', function() {}), - }); - - let { store } = setupStore({ - person: Person, - }); - - run(() => { - let person = store.createRecord('person'); - person.get('idComputed'); - - assert.equal(person.get('id'), null, 'initial created model id should be null'); - - store.updateId(person._internalModel, { id: 'john' }); - - assert.equal(person.id, 'john', 'new id should be correctly set.'); - }); - } -); - test('ID mutation (complicated)', function(assert) { assert.expect(5); let idChange = 0; diff --git a/tests/unit/store/async-leak-test.js b/tests/unit/store/async-leak-test.js index 3c3da72c9c7..814beec3c80 100644 --- a/tests/unit/store/async-leak-test.js +++ b/tests/unit/store/async-leak-test.js @@ -8,7 +8,7 @@ import { Promise } from 'rsvp'; import { attr } from '@ember-decorators/data'; import { run } from '@ember/runloop'; import Ember from 'ember'; -import { testInDebug as test } from '../../helpers/test-in-debug'; +import test from '../../helpers/test-in-debug'; class Person extends Model { @attr From 4f6c9ed2ac720d14b24e04c59e21783b8a9f51a0 Mon Sep 17 00:00:00 2001 From: Chris Thoburn Date: Thu, 4 Oct 2018 16:42:55 -0700 Subject: [PATCH 3/3] prettier --- index.js | 7 +- tests/integration/records/unload-test.js | 4 +- .../relationships/belongs-to-test.js | 307 +++++++++--------- .../relationships/has-many-test.js | 111 +++---- tests/unit/model-test.js | 74 ++--- 5 files changed, 244 insertions(+), 259 deletions(-) diff --git a/index.js b/index.js index 3d04de9be16..37e23ebcdaa 100644 --- a/index.js +++ b/index.js @@ -78,10 +78,9 @@ module.exports = { }); let withoutPrivate = new Funnel(treeWithVersion, { - exclude: [ - '-private', - isProductionEnv() && !isInstrumentedBuild() ? '-debug' : false, - ].filter(Boolean), + exclude: ['-private', isProductionEnv() && !isInstrumentedBuild() ? '-debug' : false].filter( + Boolean + ), destDir: 'ember-data', }); diff --git a/tests/integration/records/unload-test.js b/tests/integration/records/unload-test.js index 153740d5517..5cae3b46152 100644 --- a/tests/integration/records/unload-test.js +++ b/tests/integration/records/unload-test.js @@ -720,9 +720,7 @@ test('(regression) unloadRecord followed by push in the same run-loop', function ); }); -test('unloading a disconnected subgraph clears the relevant internal models', function( - assert -) { +test('unloading a disconnected subgraph clears the relevant internal models', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; run(() => { diff --git a/tests/integration/relationships/belongs-to-test.js b/tests/integration/relationships/belongs-to-test.js index 939e9b47acb..ef959776d65 100644 --- a/tests/integration/relationships/belongs-to-test.js +++ b/tests/integration/relationships/belongs-to-test.js @@ -1910,174 +1910,171 @@ test("belongsTo relationship with links doesn't trigger extra change notificatio assert.equal(count, 0); }); -test( - "belongsTo relationship doesn't trigger when model data doesn't support implicit relationship", - function(assert) { - class TestRecordData extends RecordData { - constructor(modelName, id, clientId, storeWrapper, store) { - super(modelName, id, clientId, storeWrapper, store); - delete this.__implicitRelationships; - delete this.__relationships; - } - - _destroyRelationships() {} - - _allRelatedRecordDatas() {} - - _cleanupOrphanedRecordDatas() {} - - _directlyRelatedRecordDatas() { - return []; - } - - destroy() { - this.isDestroyed = true; - this.storeWrapper.disconnectRecord(this.modelName, this.id, this.clientId); - } - - get _implicitRelationships() { - return undefined; - } - get _relationships() { - return undefined; - } +test("belongsTo relationship doesn't trigger when model data doesn't support implicit relationship", function(assert) { + class TestRecordData extends RecordData { + constructor(modelName, id, clientId, storeWrapper, store) { + super(modelName, id, clientId, storeWrapper, store); + delete this.__implicitRelationships; + delete this.__relationships; } - Chapter.reopen({ - // book is still an inverse from prior to the reopen - sections: DS.hasMany('section', { async: false }), - book1: DS.belongsTo('book1', { async: false, inverse: 'chapters' }), // incorrect inverse - book2: DS.belongsTo('book1', { async: false, inverse: null }), // correct inverse - }); + _destroyRelationships() {} - const createRecordDataFor = env.store.createRecordDataFor; - env.store.createRecordDataFor = function(modelName, id, clientId, storeWrapper) { - if (modelName === 'book1' || modelName === 'section') { - return new TestRecordData(modelName, id, clientId, storeWrapper, this); - } - return createRecordDataFor.call(this, modelName, id, clientId, storeWrapper); - }; + _allRelatedRecordDatas() {} - const data = { - data: { - type: 'chapter', - id: '1', - relationships: { - book1: { - data: { type: 'book1', id: '1' }, - }, - book2: { - data: { type: 'book1', id: '2' }, - }, - book: { - data: { type: 'book', id: '1' }, - }, - sections: { - data: [ - { - type: 'section', - id: 1, - }, - { - type: 'section', - id: 2, - }, - ], - }, - }, - }, - included: [ - { type: 'book1', id: '1' }, - { type: 'book1', id: '2' }, - { type: 'section', id: '1' }, - { type: 'book', id: '1' }, - { type: 'section', id: '2' }, - ], - }; + _cleanupOrphanedRecordDatas() {} - // Expect assertion failure as Book1 RecordData - // doesn't have relationship attribute - // and inverse is not set to null in - // DSbelongsTo - assert.expectAssertion(() => { - run(() => { - env.store.push(data); - }); - }, `Assertion Failed: We found no inverse relationships by the name of 'chapters' on the 'book1' model. This is most likely due to a missing attribute on your model definition.`); + _directlyRelatedRecordDatas() { + return []; + } - //Update setup - // with inverse set to null - // no errors thrown - Chapter.reopen({ - book1: DS.belongsTo({ async: false }), - sections: DS.hasMany('section', { async: false }), - book: DS.belongsTo({ async: false, inverse: null }), - }); + destroy() { + this.isDestroyed = true; + this.storeWrapper.disconnectRecord(this.modelName, this.id, this.clientId); + } + get _implicitRelationships() { + return undefined; + } + get _relationships() { + return undefined; + } + } + + Chapter.reopen({ + // book is still an inverse from prior to the reopen + sections: DS.hasMany('section', { async: false }), + book1: DS.belongsTo('book1', { async: false, inverse: 'chapters' }), // incorrect inverse + book2: DS.belongsTo('book1', { async: false, inverse: null }), // correct inverse + }); + + const createRecordDataFor = env.store.createRecordDataFor; + env.store.createRecordDataFor = function(modelName, id, clientId, storeWrapper) { + if (modelName === 'book1' || modelName === 'section') { + return new TestRecordData(modelName, id, clientId, storeWrapper, this); + } + return createRecordDataFor.call(this, modelName, id, clientId, storeWrapper); + }; + + const data = { + data: { + type: 'chapter', + id: '1', + relationships: { + book1: { + data: { type: 'book1', id: '1' }, + }, + book2: { + data: { type: 'book1', id: '2' }, + }, + book: { + data: { type: 'book', id: '1' }, + }, + sections: { + data: [ + { + type: 'section', + id: 1, + }, + { + type: 'section', + id: 2, + }, + ], + }, + }, + }, + included: [ + { type: 'book1', id: '1' }, + { type: 'book1', id: '2' }, + { type: 'section', id: '1' }, + { type: 'book', id: '1' }, + { type: 'section', id: '2' }, + ], + }; + + // Expect assertion failure as Book1 RecordData + // doesn't have relationship attribute + // and inverse is not set to null in + // DSbelongsTo + assert.expectAssertion(() => { run(() => { env.store.push(data); }); + }, `Assertion Failed: We found no inverse relationships by the name of 'chapters' on the 'book1' model. This is most likely due to a missing attribute on your model definition.`); - let chapter = env.store.peekRecord('chapter', '1'); - let book1 = env.store.peekRecord('book1', '1'); - let book2 = env.store.peekRecord('book1', '2'); - let book = env.store.peekRecord('book', '1'); - let section1 = env.store.peekRecord('section', '1'); - let section2 = env.store.peekRecord('section', '2'); - - let sections = chapter.get('sections'); - - assert.equal(chapter.get('book1.id'), '1'); - assert.equal(chapter.get('book2.id'), '2'); - assert.equal(chapter.get('book.id'), '1'); - - // No inverse setup created for book1 - // as Model-Data of book1 doesn't support this - // functionality. - assert.notOk(book1.get('chapter')); - assert.notOk(book2.get('chapter')); - assert.notOk(book.get('chapter')); - assert.notOk( - book1._internalModel._recordData._implicitRelationships, - 'no support for implicit relationship in custom RecordData' - ); - assert.notOk( - book2._internalModel._recordData._implicitRelationships, - 'no support for implicit relationship in custom RecordData' - ); - assert.ok( - book._internalModel._recordData._implicitRelationships, - 'support for implicit relationship in default RecordData' - ); + //Update setup + // with inverse set to null + // no errors thrown + Chapter.reopen({ + book1: DS.belongsTo({ async: false }), + sections: DS.hasMany('section', { async: false }), + book: DS.belongsTo({ async: false, inverse: null }), + }); + + run(() => { + env.store.push(data); + }); - // No inverse setup is created for section - assert.notOk(section1.get('chapter')); - assert.notOk(section2.get('chapter')); + let chapter = env.store.peekRecord('chapter', '1'); + let book1 = env.store.peekRecord('book1', '1'); + let book2 = env.store.peekRecord('book1', '2'); + let book = env.store.peekRecord('book', '1'); + let section1 = env.store.peekRecord('section', '1'); + let section2 = env.store.peekRecord('section', '2'); + + let sections = chapter.get('sections'); + + assert.equal(chapter.get('book1.id'), '1'); + assert.equal(chapter.get('book2.id'), '2'); + assert.equal(chapter.get('book.id'), '1'); + + // No inverse setup created for book1 + // as Model-Data of book1 doesn't support this + // functionality. + assert.notOk(book1.get('chapter')); + assert.notOk(book2.get('chapter')); + assert.notOk(book.get('chapter')); + assert.notOk( + book1._internalModel._recordData._implicitRelationships, + 'no support for implicit relationship in custom RecordData' + ); + assert.notOk( + book2._internalModel._recordData._implicitRelationships, + 'no support for implicit relationship in custom RecordData' + ); + assert.ok( + book._internalModel._recordData._implicitRelationships, + 'support for implicit relationship in default RecordData' + ); - // Removing the sections - // shouldnot throw error - // as Model-data of section - // doesn't support implicit Relationship - run(() => { - chapter.get('sections').removeObject(section1); - assert.notOk(section1._internalModel._recordData._implicitRelationships); + // No inverse setup is created for section + assert.notOk(section1.get('chapter')); + assert.notOk(section2.get('chapter')); - chapter.get('sections').removeObject(section2); - assert.notOk(section2._internalModel._recordData._implicitRelationships); - }); + // Removing the sections + // shouldnot throw error + // as Model-data of section + // doesn't support implicit Relationship + run(() => { + chapter.get('sections').removeObject(section1); + assert.notOk(section1._internalModel._recordData._implicitRelationships); - assert.equal(chapter.get('sections.length'), 0); + chapter.get('sections').removeObject(section2); + assert.notOk(section2._internalModel._recordData._implicitRelationships); + }); - // Update the current state of chapter by - // adding new sections - // shouldnot throw error during - // setup of implicit inverse - run(() => { - sections.addObject(env.store.createRecord('section', { id: 3 })); - sections.addObject(env.store.createRecord('section', { id: 4 })); - sections.addObject(env.store.createRecord('section', { id: 5 })); - }); - assert.equal(chapter.get('sections.length'), 3); - assert.notOk(sections.get('firstObject')._internalModel._recordData._implicitRelationships); - } -); + assert.equal(chapter.get('sections.length'), 0); + + // Update the current state of chapter by + // adding new sections + // shouldnot throw error during + // setup of implicit inverse + run(() => { + sections.addObject(env.store.createRecord('section', { id: 3 })); + sections.addObject(env.store.createRecord('section', { id: 4 })); + sections.addObject(env.store.createRecord('section', { id: 5 })); + }); + assert.equal(chapter.get('sections.length'), 3); + assert.notOk(sections.get('firstObject')._internalModel._recordData._implicitRelationships); +}); diff --git a/tests/integration/relationships/has-many-test.js b/tests/integration/relationships/has-many-test.js index f2a2f73dd0f..cde132ce40a 100644 --- a/tests/integration/relationships/has-many-test.js +++ b/tests/integration/relationships/has-many-test.js @@ -959,75 +959,72 @@ test('A hasMany relationship can be reloaded if it was fetched via ids', functio }); }); -skip( - 'A hasMany relationship can be reloaded even if it failed at the first time', - async function(assert) { - assert.expect(6); +skip('A hasMany relationship can be reloaded even if it failed at the first time', async function(assert) { + assert.expect(6); - const { store, adapter } = env; + const { store, adapter } = env; - Post.reopen({ - comments: DS.hasMany('comment', { async: true }), - }); + Post.reopen({ + comments: DS.hasMany('comment', { async: true }), + }); - adapter.findRecord = function(store, type, id) { - return resolve({ - data: { - id: 1, - type: 'post', - relationships: { - comments: { - links: { related: '/posts/1/comments' }, - }, + adapter.findRecord = function(store, type, id) { + return resolve({ + data: { + id: 1, + type: 'post', + relationships: { + comments: { + links: { related: '/posts/1/comments' }, }, }, - }); - }; + }, + }); + }; - let loadingCount = -1; - adapter.findHasMany = function(store, record, link, relationship) { - loadingCount++; - if (loadingCount % 2 === 0) { - return reject({ data: null }); - } else { - return resolve({ - data: [ - { id: 1, type: 'comment', attributes: { body: 'FirstUpdated' } }, - { id: 2, type: 'comment', attributes: { body: 'Second' } }, - ], - }); - } - }; + let loadingCount = -1; + adapter.findHasMany = function(store, record, link, relationship) { + loadingCount++; + if (loadingCount % 2 === 0) { + return reject({ data: null }); + } else { + return resolve({ + data: [ + { id: 1, type: 'comment', attributes: { body: 'FirstUpdated' } }, + { id: 2, type: 'comment', attributes: { body: 'Second' } }, + ], + }); + } + }; - let post = await store.findRecord('post', 1); - let comments = post.get('comments'); - let manyArray = await comments.catch(() => { - assert.ok(true, 'An error was thrown on the first reload of comments'); - return comments.reload(); - }); + let post = await store.findRecord('post', 1); + let comments = post.get('comments'); + let manyArray = await comments.catch(() => { + assert.ok(true, 'An error was thrown on the first reload of comments'); + return comments.reload(); + }); - assert.equal(manyArray.get('isLoaded'), true, 'the reload worked, comments are now loaded'); + assert.equal(manyArray.get('isLoaded'), true, 'the reload worked, comments are now loaded'); - await manyArray.reload().catch(() => { - assert.ok(true, 'An error was thrown on the second reload via manyArray'); - }); + await manyArray.reload().catch(() => { + assert.ok(true, 'An error was thrown on the second reload via manyArray'); + }); - assert.equal( - manyArray.get('isLoaded'), - true, - 'the second reload failed, comments are still loaded though' - ); + assert.equal( + manyArray.get('isLoaded'), + true, + 'the second reload failed, comments are still loaded though' + ); - let reloadedManyArray = await manyArray.reload(); + let reloadedManyArray = await manyArray.reload(); - assert.equal( - reloadedManyArray.get('isLoaded'), - true, - 'the third reload worked, comments are loaded again' - ); - assert.ok(reloadedManyArray === manyArray, 'the many array stays the same'); - } -); + assert.equal( + reloadedManyArray.get('isLoaded'), + true, + 'the third reload worked, comments are loaded again' + ); + assert.ok(reloadedManyArray === manyArray, 'the many array stays the same'); +}); test('A hasMany relationship can be directly reloaded if it was fetched via links', function(assert) { assert.expect(6); diff --git a/tests/unit/model-test.js b/tests/unit/model-test.js index f73a1512204..730c478cdf1 100644 --- a/tests/unit/model-test.js +++ b/tests/unit/model-test.js @@ -1528,59 +1528,53 @@ test('setting the id after model creation should correctly update the id', funct }); }); -test( - 'updating the id with store.setRecordId should correctly when the id property is watched', - function(assert) { - assert.expect(2); +test('updating the id with store.setRecordId should correctly when the id property is watched', function(assert) { + assert.expect(2); - const Person = DS.Model.extend({ - name: DS.attr('string'), - idComputed: computed('id', function() {}), - }); + const Person = DS.Model.extend({ + name: DS.attr('string'), + idComputed: computed('id', function() {}), + }); - let { store } = setupStore({ - person: Person, - }); + let { store } = setupStore({ + person: Person, + }); - run(() => { - let person = store.createRecord('person'); - person.get('idComputed'); + run(() => { + let person = store.createRecord('person'); + person.get('idComputed'); - assert.equal(person.get('id'), null, 'initial created model id should be null'); + assert.equal(person.get('id'), null, 'initial created model id should be null'); - store.setRecordId('person', 'john', person._internalModel.clientId); + store.setRecordId('person', 'john', person._internalModel.clientId); - assert.equal(person.id, 'john', 'new id should be correctly set.'); - }); - } -); + assert.equal(person.id, 'john', 'new id should be correctly set.'); + }); +}); -test( - 'accessing the model id without the get function should work when id is watched', - function(assert) { - assert.expect(2); +test('accessing the model id without the get function should work when id is watched', function(assert) { + assert.expect(2); - const Person = DS.Model.extend({ - name: DS.attr('string'), - idComputed: computed('id', function() {}), - }); + const Person = DS.Model.extend({ + name: DS.attr('string'), + idComputed: computed('id', function() {}), + }); - let { store } = setupStore({ - person: Person, - }); + let { store } = setupStore({ + person: Person, + }); - run(() => { - let person = store.createRecord('person'); - person.get('idComputed'); + run(() => { + let person = store.createRecord('person'); + person.get('idComputed'); - assert.equal(person.get('id'), null, 'initial created model id should be null'); + assert.equal(person.get('id'), null, 'initial created model id should be null'); - store.setRecordId('person', 'john', person._internalModel.clientId); + store.setRecordId('person', 'john', person._internalModel.clientId); - assert.equal(person.id, 'john', 'new id should be correctly set.'); - }); - } -); + assert.equal(person.id, 'john', 'new id should be correctly set.'); + }); +}); test('ID mutation (complicated)', function(assert) { assert.expect(5);