firestore.js

    0

    0

    This code creates a Firebase instance, and then imports the necessary libraries. It then exports the following functions:

    get: Returns a list of documents in the given Firebase collection.

    add: Adds a document to the given Firebase collection.

    update: Updates a document in the given Firebase collection.

    delete: Removes a document from the given Firebase collection.

    import {db} from "./Firebase.config";
    import {collection, doc} from "firebase/firestore";
    import {getDocs, addDoc,updateDoc,deleteDoc} from "firebase/firestore";
    
    export const FireStore = {
      get: async (collectionName) => {
        try {
          const docRef = collection(db, collectionName)
          const response = await getDocs(docRef);
          let responseData = {};
          let ids = [];
          if (response.docs.length > 0) {
            response.forEach((doc) => {
              responseData[doc.id] = {
                ...doc.data(),
                id: doc.id
              };
              ids.push(doc.id);
            });
            return {data: {ids: ids, entities: responseData}};
          }
          return {data: {ids: [], entities: {}}};
        } catch (e) {
          console.log(e);
        }
      },
      add: async (collectionName, data) => {
        try {
          const docRef = collection(db, collectionName);
          const response = await addDoc(docRef, data);
          return response
        } catch (e) {
          console.log(e);
        }
      },
      update: async (collectionName, data) => {
        try {
          await updateDoc(doc(db, collectionName, data.id), data);
          return await data;
        } catch (e) {
          console.log(e);
        }
      },
      delete: async (collectionName, data) => {
        try {
          await deleteDoc(doc(db, "Todos", data.id));
          return await data;
        } catch (e) {
          console.log(e);
        }
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.