I have the following spaghetti update method and I would like to improve its coding style.
This takes an incoming PUT query for a survey object and updates it accordingly.
update: function(req, res) {
var slug = req.body.slug
, errors = {}
, surveyDiff = req.body.diff;
surveyDiff.slug = slug;
// Certains fields are not supposed to be updated, therefore they need to be removed before performing the update.
var forbiddenFields = [ 'telerivetId', 'telerivetProjectId',
'votoId', 'votoApiKey', 'campaign', 'country' ];
forbiddenFields.forEach(function(forbiddenField) {
if (surveyDiff.hasOwnProperty(forbiddenField))
delete surveyDiff[forbiddenField];
});
if (Object.keys(surveyDiff).length > 1)
// We need to verify that the user is logged and is the author of the current survey.
Session.getUser(req.cookies.logged.token, function(err, user) {
var updateSurvey = function(surveyDiff) {
// Once all verifications are done, we can safely update the survey.
Survey.update({ slug: slug, user: user.phoneNumber }, surveyDiff)
.exec(function(err, surveys) {
if (!err)
res.json({ success: true, survey: surveys[0] });
else
res.json({ success: false });
});
};
// The order property correspond to a parent model called SurveyGroup, therefore this one is updated separately
if (!surveyDiff.hasOwnProperty('order'))
updateSurvey(surveyDiff);
else
Survey.findOne({ slug: slug }).exec(function(err, survey) {
SurveyGroup.update({ id: survey.surveyGroup }, { order: surveyDiff.order },
function(err, surveyGroup) {
console.log('update survey group', err, surveyGroup);
delete surveyDiff.position;
if (!err) updateSurvey(surveyDiff);
else res.json({ success: false });
});
});
});
else res.json({ success: false });
}
This code is running on node.js using sails.js and waterline.js.