Permalink
Browse files

feat(entity): Create child when new, upon adding

  • Loading branch information...
RWOverdijk committed Mar 4, 2016
1 parent d474ca8 commit a2ff99d9517fec200d2730b7c7a9fdfe811db7fb
Showing with 23 additions and 7 deletions.
  1. +23 −7 src/entity.js
@@ -140,24 +140,40 @@ export class Entity {
/**
* Add an entity to a collection (persist).
*
* When given entity has data, create the entity and set up the relation.
*
* @param {Entity|number} entity Entity or id
* @param {string} [property] The name of the property
*
* @return {Promise}
*/
addCollectionAssociation(entity, property) {
property = property || getPropertyForAssociation(this, entity);
let idToAdd = entity;
let body = undefined;
let url = [this.getResource(), this.id, property];
if (entity instanceof Entity) {
if (!entity.id) {
return Promise.resolve(null);
}
if (this.isNew()) {
throw new Error('Cannot add association to entity that does not have an id.');
}
if (!(entity instanceof Entity)) {
url.push(entity);
idToAdd = entity.id;
return this.getTransport().create(url.join('/'));
}
return this.getTransport().create([this.getResource(), this.id, property, idToAdd].join('/'));
if (entity.isNew()) {
// Entity is new! Don't supply an ID, and just pass in the child.
body = entity.asObject();
} else {
// Entity isn't new, just add id to url.
url.push(entity.id);
}
return this.getTransport().create(url.join('/'), body)
.then(created => {
return entity.setData(created).markClean();
});
}
/**

0 comments on commit a2ff99d

Please sign in to comment.