From 315d30b42623693e4b50198da853c04d996a130c Mon Sep 17 00:00:00 2001 From: Benjamin Wilson Friedman Date: Sun, 15 Oct 2017 21:15:30 -0700 Subject: [PATCH] Fix for beforeSave with increment causing key to be Dropped (#4259) * Fixes an issue where a beforeSave hook could cause a numeric val to be dropped in response. * Use hasOwnProperty to check instead * Remove redundant set --- spec/CloudCode.spec.js | 39 +++++++++++++++++++++++++++++++++++++++ src/RestWrite.js | 5 +++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/spec/CloudCode.spec.js b/spec/CloudCode.spec.js index 5c3ca5ae..1de2551a 100644 --- a/spec/CloudCode.spec.js +++ b/spec/CloudCode.spec.js @@ -1037,6 +1037,45 @@ describe('Cloud Code', () => { }) }); + /** + * Checks that incrementing a value to a zero in a beforeSave hook + * does not result in that key being omitted from the response. + */ + it('before save increment does not return undefined', (done) => { + Parse.Cloud.define("cloudIncrementClassFunction", function (req, res) { + const CloudIncrementClass = Parse.Object.extend("CloudIncrementClass"); + const obj = new CloudIncrementClass(); + obj.id = req.params.objectId; + obj.save().then( + function (savedObj) { + res.success(savedObj); + }); + }); + + Parse.Cloud.beforeSave("CloudIncrementClass", function (req, res) { + const obj = req.object; + if(!req.master) { + obj.increment('points', -10); + obj.increment('num', -9); + } + res.success(); + }); + + const CloudIncrementClass = Parse.Object.extend('CloudIncrementClass'); + const obj = new CloudIncrementClass(); + obj.set('points', 10); + obj.set('num', 10); + obj.save(null, {useMasterKey: true}) + .then(function() { + Parse.Cloud.run('cloudIncrementClassFunction', { objectId: obj.id }) + .then(function(savedObj) { + expect(savedObj.get('num')).toEqual(1); + expect(savedObj.get('points')).toEqual(0); + done(); + }); + }); + }); + describe('cloud jobs', () => { it('should define a job', (done) => { expect(() => { diff --git a/src/RestWrite.js b/src/RestWrite.js index 9415529c..8dd13a32 100644 --- a/src/RestWrite.js +++ b/src/RestWrite.js @@ -1195,9 +1195,10 @@ RestWrite.prototype._updateResponseWithData = function(response, data) { const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK); this.storage.fieldsChangedByTrigger.forEach(fieldName => { const dataValue = data[fieldName]; - const responseValue = response[fieldName]; - response[fieldName] = responseValue || dataValue; + if(!response.hasOwnProperty(fieldName)) { + response[fieldName] = dataValue; + } // Strips operations from responses if (response[fieldName] && response[fieldName].__op) {