Skip to content

Instantly share code, notes, and snippets.

@aboveStars
Created May 30, 2024 17:07
Show Gist options
  • Save aboveStars/847e47ad3ead41e90eb4041f7b756e0b to your computer and use it in GitHub Desktop.
Save aboveStars/847e47ad3ead41e90eb4041f7b756e0b to your computer and use it in GitHub Desktop.
Apidon Database Updates (Venus)
import { firestore } from "@/firebase/adminApp";
import { NextApiRequest, NextApiResponse } from "next";
const handleAuthorization = (authorization: string | undefined) => {
const updateAPIKey = process.env.VENUS_UPDATE_KEY;
if (!updateAPIKey) return false;
if (!authorization) return false;
return updateAPIKey === authorization;
};
async function getAllUsers() {
try {
const usersCollectionQuery = await firestore.collection("/usernames").get();
const allUsernames = usersCollectionQuery.docs.map((u) => u.id);
return allUsernames;
} catch (error) {
console.error("Error on getting all users: \n", error);
return false;
}
}
async function addFrenscoreToUserDoc(username: string) {
try {
const userDocRef = firestore.doc(`/users/${username}`);
await userDocRef.update({
frenScore: 0,
});
return true;
} catch (error) {
console.error("Error while adding fren score: \n", error);
return false;
}
}
async function handleFrenscoreUpdate(users: string[]) {
try {
await Promise.all(users.map((u) => addFrenscoreToUserDoc(u)));
return true;
} catch (error) {
console.error(
"Error while executing addFrenscoreToUserDoc promises...: \n",
error
);
return false;
}
}
async function createFrenletsDocAndTagsArray(username: string) {
try {
await firestore.doc(`/users/${username}/frenlets/frenlets`).set({
tags: ["general"],
});
return true;
} catch (error) {
console.error(
"Error while creating frenlets doc and tags array: \n",
error
);
return false;
}
}
async function handleFrenletsDocUpdate(users: string[]) {
try {
await Promise.all(users.map((u) => createFrenletsDocAndTagsArray(u)));
return true;
} catch (error) {
console.error(
"Error while executing createFrenletsDocAndTagsArray promises...: \n",
error
);
return false;
}
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { authorization } = req.headers;
const authResult = handleAuthorization(authorization);
if (!authResult) return res.status(401).send("Unauthorized");
console.log("Frenlet Update Started....");
console.log("----------------");
console.log("Getting all users....");
const allUsers = await getAllUsers();
if (!allUsers) return res.status(500).send("Internal Server Error");
console.log("Getting all users done.");
console.log("----------------");
console.log("Adding frenscore to all users....");
const handleFrenscoreUpdateResult = await handleFrenscoreUpdate(allUsers);
if (!handleFrenscoreUpdateResult)
return res.status(500).send("Internal Server Error");
console.log("Adding frenscore to all users done.");
console.log("----------------");
console.log("Creating frenlets doc for all users....");
const handleFrenletsDocUpdateResult = await handleFrenletsDocUpdate(allUsers);
if (!handleFrenletsDocUpdateResult)
return res.status(500).send("Internal Server Error");
console.log("Creating frenlets doc for all users done.");
console.log("----------------");
console.log("Frenlet Update is done.");
return res.status(200).send("OK");
}
import { NotificationData, NotificationDocData } from "@/components/types/User";
import { firestore } from "@/firebase/adminApp";
import { NextApiRequest, NextApiResponse } from "next";
const handleAuthorization = (authorization: string | undefined) => {
const updateAPIKey = process.env.VENUS_UPDATE_KEY;
if (!updateAPIKey) return false;
if (!authorization) return false;
return updateAPIKey === authorization;
};
async function getAllUsers() {
try {
const usersCollectionQuery = await firestore.collection("/usernames").get();
const allUsernames = usersCollectionQuery.docs.map((u) => u.id);
return allUsernames;
} catch (error) {
console.error("Error on getting all users: \n", error);
return false;
}
}
async function updateNotifications(username: string) {
const newNotificationArray: NotificationData[] = [];
try {
const notificationCollection = await firestore
.collection(`/users/${username}/notifications`)
.get();
for (const notificatonDoc of notificationCollection.docs) {
const notificatonOldData = notificatonDoc.data() as {
cause: "like" | "follow" | "comment" | "frenlet";
sender: string;
notificationTime: number;
seen: boolean;
};
if (!notificatonOldData) return false;
const newNotificationObject: NotificationData = {
cause: notificatonOldData.cause,
sender: notificatonOldData.sender,
ts: notificatonOldData.notificationTime,
};
newNotificationArray.push(newNotificationObject);
}
const newNotificationDocData: NotificationDocData = {
notifications: newNotificationArray,
lastOpenedTime: Date.now(),
};
await firestore
.doc(`/users/${username}/notifications/notifications`)
.set({ ...newNotificationDocData });
return true;
} catch (error) {
console.error("Error on updating notifications: \n", error);
return false;
}
}
async function executeUpdateNotifications(usernames: string[]) {
try {
await Promise.all(usernames.map((u) => updateNotifications(u)));
return true;
} catch (error) {
console.error("Error on executing updateNotifications: \n", error);
return false;
}
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { authorization } = req.headers;
const authResult = handleAuthorization(authorization);
if (!authResult) return res.status(401).send("Unauthorized");
const allUsernames = await getAllUsers();
if (!allUsernames) return res.status(500).send("Internal Server Error");
const updateNotificationsResult = await executeUpdateNotifications(
allUsernames
);
if (!updateNotificationsResult)
return res.status(500).send("Internal Server Error");
return res.status(200).send("OK");
}
import { firestore } from "@/firebase/adminApp";
import { NextApiRequest, NextApiResponse } from "next";
const handleAuthorization = (authorization: string | undefined) => {
const updateAPIKey = process.env.VENUS_UPDATE_KEY;
if (!updateAPIKey) return false;
if (!authorization) return false;
return updateAPIKey === authorization;
};
async function getAllUsers() {
try {
const usersCollectionQuery = await firestore.collection("/usernames").get();
const allUsernames = usersCollectionQuery.docs.map((u) => u.id);
return allUsernames;
} catch (error) {
console.error("Error on getting all users: \n", error);
return false;
}
}
async function getPostsOfUser(username: string) {
try {
const postsQuery = await firestore
.collection(`/users/${username}/posts`)
.get();
const postsDocPaths = postsQuery.docs.map((p) => p.ref.path);
return postsDocPaths;
} catch (error) {
console.error("Error on getting posts of user: \n", error);
return false;
}
}
async function getAllPostDocPaths(users: string[]) {
const postDocPaths: string[] = [];
const getPostsOfUserResults = await Promise.all(
users.map((u) => getPostsOfUser(u))
);
for (const result of getPostsOfUserResults) {
if (!result) continue;
postDocPaths.push(...result);
}
return postDocPaths;
}
async function handleUpdatePostIdField(postDocPath: string) {
try {
const postDocSnapshot = await firestore.doc(postDocPath).get();
if (!postDocSnapshot.exists) {
console.error("Post doc not found: ", postDocPath);
return false;
}
const postDocId = postDocSnapshot.ref.id;
await postDocSnapshot.ref.update({
id: postDocId,
});
return true;
} catch (error) {
console.error("Error on updating post id field: \n", error);
return false;
}
}
async function updateAllPosts(posts: string[]) {
try {
await Promise.all(posts.map((p) => handleUpdatePostIdField(p)));
return true;
} catch (error) {
console.error("Error on updating all posts: \n", error);
return false;
}
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { authorization } = req.headers;
const authResult = handleAuthorization(authorization);
if (!authResult) return res.status(401).send("Unauthorized");
console.log("postIdUpdate started...");
console.log("---------------");
console.log("Getting all users....");
const gettingAllUsersResult = await getAllUsers();
if (!gettingAllUsersResult)
return res.status(500).send("Internal Server Error");
console.log("Getting all users done.");
console.log("---------------");
console.log("Getting all post doc paths....");
const allPostDocPaths = await getAllPostDocPaths(gettingAllUsersResult);
if (!allPostDocPaths) return res.status(500).send("Internal Server Error");
console.log("Getting all post doc paths done.");
console.log("---------------");
console.log("Updating all posts....");
const updateResult = await updateAllPosts(allPostDocPaths);
if (!updateResult) return res.status(500).send("Internal Server Error");
console.log("Updating all posts done.");
console.log("---------------");
return res.status(200).send("OK");
}
import {
CommentData,
CommentDataV2,
LikeDataV2,
} from "@/components/types/Post";
import { firestore } from "@/firebase/adminApp";
import { NextApiRequest, NextApiResponse } from "next";
const handleAuthorization = (authorization: string | undefined) => {
const updateAPIKey = process.env.VENUS_UPDATE_KEY;
if (!updateAPIKey) return false;
if (!authorization) return false;
return updateAPIKey === authorization;
};
async function getAllUsers() {
try {
const usersCollectionQuery = await firestore.collection("/usernames").get();
const allUsernames = usersCollectionQuery.docs.map((u) => u.id);
return allUsernames;
} catch (error) {
console.error("Error on getting all users: \n", error);
return false;
}
}
async function getPostsOfUser(username: string) {
try {
const postsQuery = await firestore
.collection(`/users/${username}/posts`)
.get();
const postsDocPaths = postsQuery.docs.map((p) => p.ref.path);
return postsDocPaths;
} catch (error) {
console.error("Error on getting posts of user: \n", error);
return false;
}
}
async function getAllPostDocPaths(users: string[]) {
const postDocPaths: string[] = [];
const getPostsOfUserResults = await Promise.all(
users.map((u) => getPostsOfUser(u))
);
for (const result of getPostsOfUserResults) {
if (!result) continue;
postDocPaths.push(...result);
}
return postDocPaths;
}
async function handleLikeUpdate(postDocPath: string) {
try {
const likesQuery = await firestore
.doc(postDocPath)
.collection("likes")
.get();
const likes = likesQuery.docs.map((likeDoc) => {
const likerUsername = likeDoc.id;
const likeDocData = likeDoc.data();
const newLikeObject: LikeDataV2 = {
sender: likerUsername,
ts: likeDocData.likeTime,
};
return newLikeObject;
});
await firestore.doc(postDocPath).update({ likes: likes });
return true;
} catch (error) {
console.error("Error on updating likes: \n", error);
return false;
}
}
async function handleCommentUpdate(postDocPath: string) {
try {
const comments: CommentDataV2[] = [];
const commentsQuery = await firestore
.doc(postDocPath)
.collection("comments")
.get();
for (const commentDoc of commentsQuery.docs) {
const commentQueryOfThisSender = await commentDoc.ref
.collection("comments")
.get();
for (const commentDocOfThisSender of commentQueryOfThisSender.docs) {
const commentData = commentDocOfThisSender.data() as CommentData;
const newCommentData: CommentDataV2 = {
message: commentData.comment,
sender: commentData.commentSenderUsername,
ts: commentData.creationTime,
};
comments.push(newCommentData);
}
}
await firestore.doc(postDocPath).update({ comments: comments });
return true;
} catch (error) {
console.error("Error on updating comments: \n", error);
return false;
}
}
async function executeLikeUpdate(postDocPaths: string[]) {
try {
await Promise.all(postDocPaths.map((p) => handleLikeUpdate(p)));
return true;
} catch (error) {
console.error("Error on executing like update: \n", error);
return false;
}
}
async function executeCommentUpdate(postDocPath: string[]) {
try {
await Promise.all(postDocPath.map((p) => handleCommentUpdate(p)));
return true;
} catch (error) {
console.error("Error on executing comment update: \n", error);
return false;
}
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { authorization } = req.headers;
const authResult = handleAuthorization(authorization);
if (!authResult) return res.status(401).send("Unauthorized");
console.log("postOptimizationUpdate started...");
console.log("---------------");
console.log("Getting all users....");
const gettingAllUsersResult = await getAllUsers();
if (!gettingAllUsersResult)
return res.status(500).send("Internal Server Error");
console.log("Getting all users done.");
console.log("---------------");
console.log("Getting all post doc paths....");
const allPostDocPaths = await getAllPostDocPaths(gettingAllUsersResult);
if (!allPostDocPaths) return res.status(500).send("Internal Server Error");
console.log("Getting all post doc paths done.");
console.log("---------------");
console.log("Updating likes....");
const likeUpdateResult = await executeLikeUpdate(allPostDocPaths);
if (!likeUpdateResult) return res.status(500).send("Internal Server Error");
console.log("Updating likes done.");
console.log("---------------");
console.log("Updating comments....");
const commentUpdateResult = await executeCommentUpdate(allPostDocPaths);
if (!commentUpdateResult)
return res.status(500).send("Internal Server Error");
console.log("Updating comments done.");
console.log("---------------");
console.log("Post Optimization Update is done.");
return res.status(200).send("OK");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment