0

I am working on an iOS app where users can make posts and also favourite other users' posts. A user will be able to view all the posts s/he has favourited in a UITableView.

To achieve this, I am using Firebase as the backend, I have included my current database structure below.

root
  |
  ---posts
  |     |-post1
  |     |   |-title: "Post One Title"
  |     |   |-author: "userX"
  |     |-post2
  |     |   :
  |     :
  |     |-postN
  |
  ---users
  |     |-user1
  |         |-name: "John Doe"
  |         |-email: "example@gmail.com"
  |
  ---user-favorites
        |
        |-user1
            |-post1: true
            |-post2: true

In order to display all the favourite posts of a particular user (say user1), I currently observe the /user-favourites/user1 reference for childAdded and childRemoved events. This works fine but here is the problem: suppose post1 (which was made by userX) gets deleted, a reference to it is still in user1's favourites, with time, user1's favourites will have a lot of references pointing to non-existing posts.

How do I ensure that referential integrity is maintained, that is, if post1 is deleted by userX, post1 automatically goes away from the favourites list of user1 (and also gets removed from the UITableview automatically), additionally, if post1 gets modified (say its title is changed), the TableView of user1 automatically reflects this new title too.

Rather than code samples, I am more interested in design recommendations, especially if you have experienced and solved a problem like this. However, suggestions are welcome, and if code samples show your point, then by all means post them. Thanks.

eyeezzi
  • 635
  • 7
  • 18
  • 1
    You'd use Firebase security rules to ensure the data stays in sync: https://firebase.google.com/docs/database/security/. For a quite elaborate example, see http://stackoverflow.com/questions/37954217/is-the-way-the-firebase-database-quickstart-handles-counts-secure – Frank van Puffelen Oct 26 '16 at 04:04
  • 1
    Yes, Firebase rules are very simple individually, but when combined can be very powerful. You can use `updateChildValues` to post to multiple locations in one request and your rules can ensure the objects are created with their corresponding relations and vice versa. – Callam Oct 26 '16 at 04:10
  • @FrankvanPuffelen, I know about security rules and I can't see how they help in this situation. – eyeezzi Oct 26 '16 at 21:57
  • @Callam, I also know about fanning-out data, but again, its not apparent how your suggestion tackles this particular problem. If the question was not clear, please indicate so and I'll edit it. – eyeezzi Oct 26 '16 at 21:57

0 Answers0