Created
September 16, 2019 10:06
-
-
Save mateusduraes/8f2c52dbc8b9a741912008d8275eb67e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as functions from 'firebase-functions'; | |
import { app } from '../../../utils/admin'; | |
import { ERRORS } from '../../../consts/errors'; | |
| |
const getCountCommentsByPost = async (post: FirebaseFirestore.QueryDocumentSnapshot): Promise<number> => { | |
const comments = await post.ref.collection('comments').get(); | |
const postComments = comments.size; | |
const subCommentsPromises = comments.docs.map(comment => comment.ref.collection('subcomments').get()); | |
const subComments = await Promise.all(subCommentsPromises); | |
const totalSubcomments = subComments.map(subComment => subComment.size).reduce((prev, curr) => prev + curr, 0); | |
return postComments + totalSubcomments; | |
}; | |
| |
const getLikesByPost = async (post: FirebaseFirestore.QueryDocumentSnapshot): Promise<number> => { | |
const likes = await post.ref.collection('likes').get(); | |
const postLikes = likes.size; | |
const commentsLikes = await post.ref.collection('comments').get(); | |
const likesCommentsPromises = commentsLikes.docs.map(comment => comment.ref.collection('likes').get()); | |
const likesComments = await Promise.all(likesCommentsPromises); | |
const countLikes = likesComments.map(like => like.size).reduce((prev, curr) => prev + curr , 0); | |
return countLikes + postLikes; | |
}; | |
| |
module.exports = functions.https.onCall(async (data, context) => { | |
if (!data.slug) { | |
throw new functions.https.HttpsError('not-found', ERRORS.INVALID_EDITION); | |
} | |
| |
const db = app.firestore(); | |
const snap = await db.collection(`editions/${data.slug}/posts`) | |
.orderBy('createdAt', 'desc') | |
.get(); | |
| |
try { | |
const promises = []; | |
const totalPosts = snap.size; | |
const totalCommentsPromises = snap.docs.map(post => { | |
return getCountCommentsByPost(post); | |
}); | |
const postComments = await Promise.all(totalCommentsPromises); | |
const totalComments = postComments.reduce((prev, curr) => prev + curr, 0); | |
| |
const totalLikesPromises = snap.docs.map(post => { | |
return getLikesByPost(post); | |
}) | |
const likes = await Promise.all(totalLikesPromises); | |
likes.reduce((prev, curr) => prev + curr, 0); | |
| |
return { totalPosts, totalComments, likes }; | |
} catch (e) { | |
throw e; | |
} | |
| |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment