Skip to content

Commit 3c3f9fb

Browse files
committed
Add toJSON support.
1 parent f7e1b42 commit 3c3f9fb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

lib/api/services/JsonApiService.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,37 @@ module.exports = {
173173
return data;
174174
},
175175

176+
177+
/*
178+
* Call toJSON recursively for all objects in data
179+
*
180+
* @param {Object|array} input data
181+
* @return {Object|array} data with toJSON called for every included objects
182+
*/
183+
_toJSON: function(data) {
184+
// Empty data
185+
if (_.isEmpty(data)) {
186+
// Return [] or null
187+
return _.isArray(data) ? data : null;
188+
}
189+
190+
// Array data
191+
if (_.isArray(data)) {
192+
return data.map(obj => this._toJSON(obj));
193+
}
194+
195+
// Single data
196+
if (typeof data.toJSON === 'function') {
197+
return data.toJSON();
198+
}
199+
200+
return data;
201+
},
202+
176203
serialize: function(modelName, data) {
177204

205+
data = this._toJSON(data);
206+
178207
var returnedValue = null;
179208
if ((_.isArray(data) && depthOf(data) > 2) || (_.isObjectLike(data) && _.isArray(data) === false && depthOf(data) > 1)) {
180209
returnedValue = Serializer.serialize(modelName, data);

0 commit comments

Comments
 (0)