Skip to content
This repository has been archived by the owner on May 27, 2022. It is now read-only.

Commit

Permalink
AddCommentScreen: implement rating
Browse files Browse the repository at this point in the history
  • Loading branch information
peat-psuwit committed Nov 14, 2018
1 parent 68d26ae commit 6bfb567
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions screens/AddCommentScreen/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,39 @@ class AddCommentScreen extends React.Component {
const { comment } = this.state;
const { navigation } = this.props;
const albumId = navigation.getParam('albumId');
const collection = firestore.collection('albums')
.doc(albumId)
.collection('comments');
const albumRef = firestore.collection('albums')
.doc(albumId);
const collection = albumRef.collection('comments');

collection.add({
...comment,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
firestore.runTransaction((t) => {
return t.get(albumRef)
.then((albumDoc) => {
const { rating_count, avg_rating } = albumDoc.data();
let new_rating_count, new_avg_rating;

if (rating_count === undefined) {
new_rating_count = 1;
new_avg_rating = comment.rating;
}
else {
new_rating_count = rating_count + 1;
new_avg_rating =
((avg_rating * rating_count) + comment.rating)
/ new_rating_count;
}

const newCommentRef = collection.doc();
return Promise.all([
t.set(newCommentRef, {
...comment,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
}),
t.update(albumRef, {
rating_count: new_rating_count,
avg_rating: new_avg_rating,
}),
]);
});
}).then(() => navigation.pop());
}

Expand Down

0 comments on commit 6bfb567

Please sign in to comment.