How to join denormalized data that are at a depth of 2+ in Firebase

Here is the scenario: I have a list of topics, each topic includes posts, and each post is "liked" by a list of users. So my data looks something like this:

"topics": {
    "topic1": {
        "posts": {
            "post1": true,
            "post2": true
        }
     }
 },
 "posts": {
     "post1": {
         "title": "An awesome post",
         "likes": {
             "user1": true
         }
     },
     "post2": {
         "title": "An even better post",
         "likes": {
             "user1": true,
             "user2": true
         }
     }
 },
 "users": {
     "user1": {
         "name": "Mr. T",
         "email": "t@t.com"
     },
     "user2": {
         "name": "Mr. Hello World",
         "email": "hello@world.com"
     }
 }

I (it seems, I) know how to get all posts on a topic using Firebase.util ( http://firebase.imtqy.com/firebase-util ):

Firebase.util.intersection(
    fb.child('topics').child('topic1').child('posts'),
    fb.child('posts')
)

But now I would like for each post to contain the names of the users who liked this post. How to do it?

Nothing will likely change, but it all happens in AngularFire.

+4
1

, , . , . .

Firebase , - , , , .

HTML:

<h3>Normalizing user profiles into posts</h3>

<ul ng-controller="ctrl">
    <li ng-repeat="post in posts | orderByPriority" ng-init="user = users.$load(post.user)">
        {{user.name}}: {{post.title}}
    </li>
</ul>

JavaScript:

var app = angular.module('app', ['firebase']);
var fb = new Firebase(URL);

app.controller('ctrl', function ($scope, $firebase, userCache) {
    $scope.posts = $firebase(fb.child('posts'));
    $scope.users = userCache(fb.child('users'));
});

app.factory('userCache', function ($firebase) {
    return function (ref) {
        var cachedUsers = {};
        cachedUsers.$load = function (id) {
            if( !cachedUsers.hasOwnProperty(id) ) {
                cachedUsers[id] = $firebase(ref.child(id));
            }
            return cachedUsers[id];
        };
        cachedUsers.$dispose = function () {
            angular.forEach(cachedUsers, function (user) {
                user.$off();
            });
        };
        return cachedUsers;
    }
});
+3

Source: https://habr.com/ru/post/1536885/


All Articles