DEV Community

Desai Hardik
Desai Hardik

Posted on

Hello World

import { collection, doc, getDoc, getDocs, query, where } from "firebase/firestore";
import { db } from "src/firebase/firebase-config";

export const GetAllPost = async () => {
    try {
        const usersRef = collection(db, "users");
        const querySnapshot = await getDocs(usersRef);

        const allPosts = [];

        querySnapshot.forEach((userDoc) => {
            const userData = userDoc.data();
            const posts = userData.post || [];
            const newData = posts.map((item) => {
                return {
                    ...item,
                    userName: userData.userName,
                    fullName: userData.fullName,
                    profileUrl: userData.profileUrl,
                };
            });
            allPosts.push(...newData);
        });

        return allPosts;
    } catch (error) {
        throw new Error('Error retrieving all posts');
    }
};

export const GetDetailsFromUsername = async (username) => {
    try {
        const q = query(collection(db, "users"), where("userName", "==", username));
        const querySnapshot = await getDocs(q);

        if (querySnapshot.empty) {
            return {
                code: 404,
                message: "User not found",
            };
        }

        const user = querySnapshot.docs[0];
        const userData = user.data();

        return userData;
    } catch (error) {
        return {
            code: 500,
            message: "Internal server error",
            error: error.message,
        };
    }
}

export const GetPostDataWithPostID = async (username, postId) => {
    try {
        return await GetDetailsFromUsername(username).then(async (user) => {
            const userRef = doc(db, 'users', user.uid);
            const userDoc = await getDoc(userRef);
            if (userDoc.exists()) {
                const data = userDoc.data();
                const postData = data.post;
                const post = postData.find((item) => item.postId == postId);

                return post ? { post, user } : null;
            } else {
                console.log('User not found');

                return null;
            }
        });
    } catch (error) {
        console.error('Error finding post:', error);
        throw error;
    }
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)