Parse | Identify Changed Columns

Sometime it is important to identify if the value of the column is changed and perform a action based on it. In the parse we have an method called request.object.dirty(<column_name>). But the only issue is that this works only on the beforeSave. But most of us want to perform an action only when we are sure that data is saved. In other word we would like to do it on "afterSave".

for eg. If you want to send a email or push notification based on a status flag getting updated. We would like to do that on the "afterSave". But on "afterSave"

Here is the code how to do it.

Parse.Cloud.beforeSave("", function(request, response) {
  
  //--find the columns which got changed
  var arrChangedAttributes = new Array(); 
  var vAttributes = request.object.attributes; 

  var query = new Parse.Query(">> id >>>" +  request.object.id );
  
  //--means it is an INSERT. This is to identify it is an INSERT or UPDATE
  if(!request.object.id){
   
   request.object.set("changedColumns", "$NEW$");
      response.success();
      return;
  }
  
  query.equalTo("objectId", request.object.id);  
  query.first({
      success: function(pResult) {
        if (pResult) {
        
     for(var ax in vAttributes){
            
      if(request.object.dirty(ax)){ 
       
       console.log( ">>> dirty >>>"+ ax +"/"+request.object.get(ax)+"/"+pResult.get(ax));   
       if( request.object.get(ax) != pResult.get(ax) ){
          
        arrChangedAttributes.push(ax);
       }
      }
      }
          request.object.set("changedColumns", arrChangedAttributes.join());
        }else{
         
          console.log( "Error0"+ error.message);
          response.error("Error");
        }
        console.log( ">>> success >>>");
        response.success();
      },
      error: function(error) {
    
        console.log( "Error1"+ error.message);
        response.error("Error");
      }
    });
});

//=======================================================================


Parse.Cloud.afterSave("", function(request) { 
 
 var vChangedColumns   = request.object.get( "changedColumns");
 
    if( vChangedColumns == "$NEW$") {
         
         //-- do the action for insert
    }else{
     
     var arrChangedAttributes = vChangedColumns.split(,);
     //--do the action for update
    }
});

Comments

Popular posts from this blog

Tableau - Accessing Tableau's DB

react-bootstrap-table | header column alignment fix

Tableau : Convert ESRI shapes into Tableau Format