Skip to content

Commit c0433df

Browse files
committed
Move belongsTo relationship handling
Change from doing a saveAttributes to save fk to model, to setting fk on model and letting the natural save process commit the change. The main advantage of doing this is to prevent double operation hooks firing
1 parent 02bb00b commit c0433df

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/deserializer.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,39 @@ module.exports = function deserializer (options, cb) {
4141
if (err) return cb(err);
4242
afterDeserialize(deserializeOptions, function (err, deserializeOptions) {
4343
if (err) return cb(err);
44+
45+
belongsToRelationships(deserializeOptions);
4446
return cb(null, deserializeOptions);
4547
});
4648
});
4749
});
4850
};
51+
52+
function belongsToRelationships (options) {
53+
var data = options.data;
54+
var model = options.model;
55+
56+
if (!data || !data.data || !model || !data.data.relationships) {
57+
return;
58+
}
59+
60+
_.each(data.data.relationships, function (relationship, name) {
61+
var serverRelation = model.relations[name];
62+
if (!serverRelation) return;
63+
var type = serverRelation.type;
64+
65+
// only handle belongsTo
66+
if (type !== 'belongsTo') return;
67+
68+
var fkName = serverRelation.keyFrom;
69+
var modelTo = serverRelation.modelFrom;
70+
71+
if (!modelTo) return false;
72+
73+
if (!relationship.data) {
74+
options.result[fkName] = null;
75+
} else {
76+
options.result[fkName] = relationship.data.id;
77+
}
78+
});
79+
}

lib/relationships.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,12 @@ module.exports = function (app, options) {
1515
return next();
1616
};
1717

18-
if (ctx.method.name !== 'updateAttributes') return next();
18+
if (!ctx.method.name === 'updateAttributes') return next();
1919

2020
id = ctx.req.params.id;
2121
data = options.data;
2222
model = utils.getModelFromContext(ctx, app);
23+
2324
relationships(id, data, model);
2425

2526
next();
@@ -56,6 +57,10 @@ function relationships (id, data, model) {
5657
var serverRelation = model.relations[name];
5758
if (!serverRelation) return;
5859
var type = serverRelation.type;
60+
61+
// don't handle belongsTo in relationships function
62+
if (type === 'belongsTo') return;
63+
5964
var modelTo = serverRelation.modelTo;
6065

6166
var fkName = serverRelation.keyTo;

0 commit comments

Comments
 (0)