Skip to content

Commit 62a8e60

Browse files
committed
Do no expect relationships when serializing a record with no associations
1 parent 4c44a85 commit 62a8e60

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

lib/api/services/JsonApiService.js

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,21 @@ var createRecord = require('../blueprints/create');
1010
var destroyOneRecord = require('../blueprints/destroy');
1111
var updateOneRecord = require('../blueprints/update');
1212

13+
// Copied from http://stackoverflow.com/questions/13523951/how-to-check-the-depth-of-an-object
14+
var depthOf = function(object) {
15+
var level = 1;
16+
var key;
17+
for (key in object) {
18+
if (!object.hasOwnProperty(key)) continue;
19+
20+
if (typeof object[key] == 'object') {
21+
var depth = depthOf(object[key]) + 1;
22+
level = Math.max(depth, level);
23+
}
24+
}
25+
return level;
26+
};
27+
1328
module.exports = {
1429

1530
findRecords: findRecords,
@@ -23,9 +38,10 @@ module.exports = {
2338
for (let name in sails.models) {
2439

2540
let model = sails.models[name];
41+
let identity = pluralize(model.identity);
2642
let associations = {};
2743

28-
sails.log.verbose("Registering model " + name + " as " + pluralize(model.identity));
44+
sails.log.verbose("Registering model " + name + " as " + identity);
2945
model.associations.forEach((association) => {
3046

3147
let alias = association['alias'];
@@ -37,11 +53,21 @@ module.exports = {
3753
};
3854
});
3955

40-
Serializer.register(pluralize(model.identity), {
56+
Serializer.register(identity, {
4157
id: model.primaryKey || 'id',
4258
convertCase: this.getAttributesSerializedCaseSetting(),
4359
relationships: associations
4460
});
61+
62+
/*
63+
* Most of the time, no relationships are provided with the record.
64+
* Which is why we need a custom schema in this case
65+
*/
66+
Serializer.register(identity, 'noRelationships-' + identity, {
67+
id: model.primaryKey || 'id',
68+
convertCase: this.getAttributesSerializedCaseSetting(),
69+
relationships: {}
70+
});
4571
};
4672
},
4773

@@ -128,7 +154,12 @@ module.exports = {
128154

129155
serialize: function(modelName, data) {
130156

131-
var returnedValue = Serializer.serialize(modelName, data);
157+
var returnedValue = null;
158+
if ((_.isArray(data) && depthOf(data) > 2) || (_.isObjectLike(data) && _.isArray(data) === false && depthOf(data) > 1)) {
159+
returnedValue = Serializer.serialize(modelName, data);
160+
} else {
161+
returnedValue = Serializer.serialize(modelName, data, 'noRelationships-' + modelName);
162+
}
132163

133164
/*
134165
* To avoid the situation where many to many relationships are not described both ways

0 commit comments

Comments
 (0)