/ app / src / utils / firebase.js
firebase.js
  1  // Import the functions you need from the SDKs you need
  2  import { initializeApp, getApps } from "firebase/app";
  3  import {
  4    getFirestore,
  5    query,
  6    where,
  7  } from "firebase/firestore";
  8  import {
  9    collection,
 10    addDoc,
 11    getDocs,
 12    updateDoc,
 13    getDoc,
 14    doc,
 15  } from "firebase/firestore";
 16  
 17  import { serverTimestamp } from "firebase/firestore";
 18  const firebaseConfig = {
 19    apiKey: process.env.NEXT_PUBLIC_API_KEY,
 20    authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
 21    projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
 22    storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
 23    messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
 24    appId: process.env.NEXT_PUBLIC_APP_ID,
 25    measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
 26  };
 27  
 28  
 29  // Initialize Firebase
 30  if (!getApps().length) {
 31    const app = initializeApp(firebaseConfig);
 32    console.log("initializing firebase! ");
 33  }
 34  const db = getFirestore();
 35  
 36  
 37  export const createPersonDocument = async (userID, imageURL) => {
 38    console.log('trying to create person doc with '+ userID +" and "+ imageURL)
 39    try {
 40      const peopleCollection = collection(db, "people");
 41      const docRef = await addDoc(peopleCollection, {
 42        time: serverTimestamp(),
 43        status: 'processing',
 44        userID: userID,
 45        imageURL: imageURL || '',
 46      });
 47  
 48      console.log("Document created with ID: ", docRef.id);
 49      return docRef.id;
 50    } catch (error) {
 51      console.error("Error creating document: ", error);
 52    }
 53  };
 54  
 55  export const addSocialsToPersonDocument = async (socials, docId) => {
 56    try {
 57      if (typeof docId !== 'string') {
 58        throw new Error(`Expected docId to be a string, but got ${typeof docId}`);
 59      }
 60  
 61      const peopleCollection = collection(db, "people");
 62      const docRef = doc(peopleCollection, docId);
 63  
 64      if (!docRef || typeof docRef !== 'object' || !docRef.id) {
 65        throw new Error(`Expected docRef to be a DocumentReference, but got ${typeof docRef}`);
 66      }
 67  
 68      const socialsCollection = collection(docRef, "socials");
 69  
 70      for (let social of socials) {
 71        console.log(social);
 72        const documentData = {
 73          'score': social['score'],
 74          'url': social['url'],
 75        };
 76        await addDoc(socialsCollection, documentData);
 77      }
 78      await updateDoc(docRef, {
 79        status: 'completed',
 80      });
 81  
 82      console.log("Socials added to document with ID: ", docRef.id);
 83    } catch (error) {
 84      console.error("Error adding socials to document: ", error);
 85      try {
 86        const peopleCollection = collection(db, "people");
 87        const newPersonDoc = await addDoc(peopleCollection, {
 88          time: serverTimestamp(),
 89          status: 'processing',
 90  
 91        });
 92        const newSocialsCollection = collection(newPersonDoc, "socials");
 93        for (let social of socials) {
 94          const documentData = {
 95            'score': social['score'],
 96            'url': social['url'],
 97          };
 98          await addDoc(newSocialsCollection, documentData);
 99        }
100        console.log("New person document and socials created due to error.");
101      } catch (newError) {
102        console.error("Error creating new person document and socials: ", newError);
103      }
104    }
105  };
106  
107  // get all messages with role assistant and privacyOption public
108  export const getPeopleFromFirestore =
109    async () => {
110      try {
111        const peopleCollection = collection(db, "people");
112        const q = query(peopleCollection);
113        const querySnapshot = await getDocs(q);
114        const people = [];
115        for (let doc of querySnapshot.docs) {
116          const person = doc.data();
117          const socialsCollection = collection(doc.ref, "socials");
118          const socialsSnapshot = await getDocs(socialsCollection);
119          const socials = [];
120          socialsSnapshot.forEach((socialDoc) => {
121            if(socialDoc.data().score >= 60) {
122              socials.push(socialDoc.data());
123            }
124          });
125          socials.sort((a, b) => b.score - a.score);
126       
127          person.socials = socials;
128          try {
129            person.time = new Date(person.time.seconds * 1000).toString();
130          } catch (error) {
131            return person.time;
132          }
133          person.id = doc.id; // Adding the id of the person to the data
134          if(socials.length > 0) {
135            person.socials = socials;
136            people.push(person);
137          }
138        }
139    
140        return people;
141      } catch (error) {
142        console.error(
143          "Error fetching messages:",
144          error
145        );
146        throw error;
147      }
148    };
149  
150    export const getPersonFromFirestore = async (docID) => {
151      try {
152        const personDoc = doc(db, "people", docID);
153        const personSnapshot = await getDoc(personDoc);
154        if (!personSnapshot.exists()) {
155          console.log("No such document!");
156          return null;
157        } else {
158          const person = personSnapshot.data();
159          const socialsCollection = collection(db, "people", docID, "socials");
160          const socialsSnapshot = await getDocs(socialsCollection);
161          const socials = [];
162          socialsSnapshot.forEach((socialDoc) => {
163            if(socialDoc.data().score >= 60) {
164              socials.push(socialDoc.data());
165            }
166          });
167          socials.sort((a, b) => b.score - a.score);
168       
169          person.socials = socials;
170          try {
171            person.time = new Date(person.time.seconds * 1000).toString();
172          } catch (error) {
173            return person.time;
174          }
175          person.id = personSnapshot.id; // Adding the id of the person to the data
176          if(socials.length > 0) {
177            person.socials = socials;
178          }
179          return person;
180        }
181      } catch (error) {
182        console.error(
183          "Error fetching person:",
184          error
185        );
186        throw error;
187      }
188    };
189  
190    export const updatePersonDoc = async (personId, data) => {
191      const personDoc = doc(db, "people", personId);
192      await updateDoc(personDoc, data);
193    };
194  
195  
196  export default db;