Skip to content

Commit

Permalink
Add JSONBuilder.appendObject()
Browse files Browse the repository at this point in the history
Will append an object property to the building object by recursively calling toJSONObject() on each own property.

This is a preparation for linagora#58
  • Loading branch information
thomascube authored and fabienmoyon committed Oct 13, 2017
1 parent fe2cb79 commit 19b1b13
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/utils/JSONBuilder.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,33 @@ export default class JSONBuilder {
return this;
}

/**
* Will append the _value_ object to the building object by recursively calling toJSONObject()
* on each child if an object.
*
* @param name {String} The name to use as key.
* @param value {Array} The `Object` to append
*/
appendObject(name, value) {
let key, obj = {};

Utils.assertRequiredParameterIsObject(value, 'value');

for (key in value) {
if (value.hasOwnProperty(key)) {
if (typeof value[key] === 'object' && value[key].toJSONObject) {
obj[key] = value[key].toJSONObject();
} else {
obj[key] = value[key];
}
}
}

this.append(name, obj);

return this;
}

/**
* @return an object with all appended values
**/
Expand Down
33 changes: 33 additions & 0 deletions test/common/utils/JSONBuilder.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,37 @@ describe('The JSONBuilder class', function() {

});

describe('The appendObject method', function() {

var obj = { one: 1, two: 2 };
var Child = function(val) {
this.prop = val;
this.toJSONObject = function() {
return { value: this.prop };
};
};
var complex = { foo: 'foo', child: new Child('bar') };

it('should throw an Error if the name is undefined', function() {
expect(function() {
new jmap.JSONBuilder().appendObject(undefined, {});
}).to.throw(Error);
});

it('should throw an Error if date is not an Object', function() {
expect(function() {
new jmap.JSONBuilder().appendObject('obj', []);
}).to.throw(Error);
});

it('should append a clone of the object value', function() {
expect(new jmap.JSONBuilder().appendObject('obj', obj).build()).to.deep.equal({ obj: obj });
});

it('should call toJSONObject() on object elements', function() {
expect(new jmap.JSONBuilder().appendObject('obj', complex).build()).to.deep.equal({ obj: { foo: 'foo', child: { value: 'bar' } } });
});

});

});

0 comments on commit 19b1b13

Please sign in to comment.