Created
May 5, 2023 20:52
-
-
Save aboveStars/bdfcdf718466980ab255820fc5f35e30 to your computer and use it in GitHub Desktop.
Creating "like activities" data for users in Firebase with typescript.
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 { NextApiRequest, NextApiResponse } from "next"; | |
import { fieldValue, firestore } from "../../firebase/adminApp"; | |
export default async function handler( | |
req: NextApiRequest, | |
res: NextApiResponse | |
) { | |
try { | |
const usersDocs = (await firestore.collection("users").get()).docs; | |
const addedLikesDocUsername: string[] = []; | |
for (const userDoc of usersDocs) { | |
const userPostsDocs = (await userDoc.ref.collection("posts").get()).docs; | |
if (userPostsDocs.length > 0) | |
for (const userPostDoc of userPostsDocs) { | |
const likesDocs = (await userPostDoc.ref.collection("likes").get()) | |
.docs; | |
if (likesDocs.length > 0) | |
for (const likeDoc of likesDocs) { | |
const likerUsername = likeDoc.id; | |
const likeActivityData = { | |
likeTime: likeDoc.data().likeTime, | |
likedPostDocPath: userPostDoc.ref.path, | |
}; | |
if (addedLikesDocUsername.includes(likerUsername)) { | |
await firestore | |
.doc(`users/${likerUsername}/activites/likes`) | |
.update({ | |
likesDatas: fieldValue.arrayUnion({ ...likeActivityData }), | |
}); | |
} else { | |
await firestore | |
.doc(`users/${likerUsername}/activites/likes`) | |
.set({ | |
likesDatas: fieldValue.arrayUnion({ ...likeActivityData }), | |
}); | |
addedLikesDocUsername.push(likerUsername); | |
} | |
} | |
} | |
} | |
} catch (error) { | |
console.error("Error while update.", error); | |
return res.status(400).json({ Bad: "Very badd" }); | |
} | |
return res.status(200).json({ | |
status: "Successfull", | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment