EmberFire Relationship Persistance

54 views Asked by At

Using EmberFire, I'm trying to work with related sets of data. In this case, a Campaign has many Players and Players have many Campaigns.

When I want to add a player to campaign, I understand that I can push the player object to campaign.players, save the player, and then save the campaign. This will update both records so that the relationship is cemented. This works fine.

My question is a hypothetical on how to handle failures when saving one or both records.

For instance, how would you handle an occasion whereby saving the player record succeeded (thus adding a corresponding campaign ID to its campaigns field), but saving the campaign then failed (thus failing to add the player to its players field). It seems like in this case you'd open yourself up to the potential of some very messy data.

I was considering taking a "snapshot" of both records in question and then resetting them to their previous states if one update fails, but this seems like it's going to create some semi-nightmarish code.

Thoughts?

1

There are 1 answers

1
Renaud Tarnec On

I guess you are using the Real Time Database. If you use the update() method with different paths "you can perform simultaneous updates to multiple locations in the JSON tree with a single call to update()"

Simultaneous updates made this way are atomic: either all updates succeed or all updates fail.

From the documentation: https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields

So, in your case, you should do something like the following but many variations are possible as soon as the updates object holds all the simultaneous updates:

  var updates = {};
  updates['/campaigns/players/' + newPlayerKey] = playerData;
  updates['/players/campaigns/' + campaignKey] = "true";

  return firebase.database().ref().update(updates);