FireStor

    0

    0

    The above code first imports the necessary libraries: firebase, collection, doc, getDocs, addDoc, updateDoc, and deleteDoc. The firestore module then exports four functions: get, add, update, and delete.

    The get function takes a collection name (in this case, "Todos") as an input and returns a Promise that resolves with a data object containing the documents in the collection. The add function takes a data object and a collection name (in this case, "Todos") and returns a Promise that resolves with the updated data object in the given collection. The update function takes a data object and a collection name (in this case, "Todos") and resolves with the updated data object in the given collection, with the added document(s) included. The delete function takes a collection name (in this case, "Todos") and a data object and resolves with a Promise that resolves with the deleted data object in the given collection.

    Library: react

    import { db } from "./firebase";
    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.