2

In my afterSave on a certain Class in Parse Cloud Code, I'm setting the appropriate ACL and then saving the same object again. I have a Push notification going on in that afterSave method, but doing save() in afterSave I think is causing the notifications to be pushed twice or thrice.

How can I handle this situation? Is there a way to save such that the afterSave is not called again? Thoughts? Help is much appreciated! Thanks!

John Doe
  • 1,005
  • 2
  • 8
  • 23

1 Answers1

5

Depending on when/how you want to send the PUSH, you might use the existed() method to check for the first time a particular instance of your class is being saved. That's what I do for an alert class that generates PUSH notifications. You can simply do:

if (request.object.existed() === false) { 
    // It's a new object 
} else { 
    // It's an existing object
}
mbm29414
  • 11,558
  • 6
  • 56
  • 87
  • Thanks @mbm29414 Yes, but I need to send out push notifications on updates as well. Your solution will only work if I need to send out push notification only on create and not on update, correct? – John Doe Nov 01 '14 at 23:06
  • @JohnDoe Well, my solution allows you to differentiate between new/updated items. I've been looking myself, but can't find any way to determine which fields were updated in `beforeSave` or `afterSave`. What I've done to differentiate between what "kind" of save I'm doing is to add status flag fields. That way, you aren't preventing the trigger, but you're not executing the same code every time. – mbm29414 Nov 02 '14 at 02:49
  • Because I couldn't find a better solution, I think I'll go with the flagging idea. Thanks! – John Doe Nov 12 '14 at 01:25
  • 1
    @JohnDoe Yeah, I agree it's a bit of a hack. I think Parse is still growing as a platform. Hopefully, they'll make `beforeSave` and `afterSave` more like SQL Server's triggers, where you can access the full state of an object and what changed. – mbm29414 Nov 12 '14 at 12:41