Badger 29
Badger 29

Reputation: 113

Can I use rxjs to filter an Observable against a string array of id's

Im setting up Access Control for an angular app and have modeled my User object like this: -User --firstName --phoneNumber --posts[] <--- String array of post id's

getPosts(): Observable<any[]> {
    return this.postsCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = a.payload.doc.data();
          const data2 = { id: a.payload.doc.id, ...data};
          this.hasPostAccess(data2);
          return { id: a.payload.doc.id, ...data};
        });
      })
    );
  }

  private hasPostAccess(data: any) {
    const inspect = obj => {
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          // console.log(`${prop}: ${obj[prop]}`);
          if (prop === 'id') {
            console.log(obj[prop]);
            const PostId = obj[prop];
            const currentUser = JSON.stringify(localStorage.getItem('user'));
            if (currentUser.search(PostId) === -1) {
              console.log('Denied: ' + PostId);
            } else {
              console.log('Allowed: ' + PostId);
            }
            console.log('Current USER: ' + JSON.stringify(currentUser));
            // if (currentUser(PostId) > -1) {
            //   console.log('Allowed: ' + PostId);
            // } else {
            //   console.log('Denied: ' + PostId);
            // }
          }
        }
      }
    };
    inspect(data);
  }

I want to show all posts that belong to the user. So when I subscribe to the getPosts Observable, this must filter the posts and return only the posts id's that are stored in the User's post array.

Upvotes: 0

Views: 73

Answers (1)

Badger 29
Badger 29

Reputation: 113

getPosts(): Observable<any[]> {
    const currentUser: User = JSON.parse(localStorage.getItem('user'));
    const userPosts  = currentUser.posts;
    return this.postsCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = { id: a.payload.doc.id, ...data};
          const filteredPosts = _.filter(data, (p) => 
          _.includes(currentUser, p.postId));
          return filteredPosts;
        });
      })
    );
  }

Upvotes: 0

Related Questions