0
votes

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 {

          }

      }

    });


  });
2

2 Answers

1
votes

The problem was actually that I wanted the beforeSave be active if the request is sent by user, not by cloud code. I solved it by using if (req.master)which will directly result in success, else if the request is done by the user, the codes in the afterSave are implemented.

0
votes

First, the answer to your last question is no. It is not possible to skip the beforeSave trigger. It will always be called when you save an object.

The best option in your case is probably to save the post in the following way instead of using the master key:

result[0].save(null, {sessionToken: req.user.getSessionToken()});

That would populate the req.user object in the post beforeSave method as normal and your user verification code would work.