Parse-server: Parse Server - Cloud Code beforeSave and afterSave effect each other

Created on 3 Mar 2016  路  4Comments  路  Source: parse-community/parse-server

In my parse-server cloud code, I have one beforeSave and one afterSave function. The beforeSave is a verification about "which user makes the saving" to the "post" table. The afterSave function upates an object in the "post" table when a comment is saved to the "comments" table. However, the "result[0].save(null, { useMasterKey: true });" part start the beforeSave function again, and as the cloud is doing the saving and there is no user, because of the user verification in the "beforeSave" part, the saving can not be done. It is a bit complicated, hope I could explained it well, is there a way to by pass the beforeSave method when the saving is done from the cloud?

  Parse.Cloud.beforeSave('post', function (req, res) {




  });




  Parse.Cloud.afterSave('comment', function(req) {


    var post = Parse.Object.extend('post');
    var query = new Parse.Query(post);
    query.equalTo('userid', req.user.id);
    query.find({

      success: function(result) {

          if ( result.length > 0 ) {


              result[0].set('commented', 'yes');
              result[0].save(null, { useMasterKey: true });

          }

          else {

          }

      }

    });


  });

Most helpful comment

If you only want the beforeSave to run for users, you can see if the save request is done by master and abort... if (request.master) { return response.success(); }

You could add granularity and do this by setting another flag on the object, which no one else knows about... such as results[0].set('mySpecialFlag', true); and in the before save, check if request.master is set and mySpecialFlag is set, remove it, and abort as above.

All 4 comments

In your beforeSave function you can just check if masterKey is used by doing
request.master == true

Thank you lastMuvie, but the problem is not about permissions, there is an if condition in the beforeSave part which verificates if the current user id is the same with the saved object user ID part. But when the afterSave starts, the saving is not by the user and there the if condition returns false. I need to by-pass the beforeSave part when the action is taken by the afterSave part, but not by-pass it when the action is taken by the user via the app.

If you only want the beforeSave to run for users, you can see if the save request is done by master and abort... if (request.master) { return response.success(); }

You could add granularity and do this by setting another flag on the object, which no one else knows about... such as results[0].set('mySpecialFlag', true); and in the before save, check if request.master is set and mySpecialFlag is set, remove it, and abort as above.

Thank you very much gfosco, was working on this for hours.

Was this page helpful?
0 / 5 - 0 ratings