AddItinerary

 avatar
unknown
typescript
3 years ago
1.7 kB
4
Indexable
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { Firestore, getFirestore, collection, setDoc, addDoc, getDoc, doc } from "firebase/firestore";
import { Itinerary } from "./Itinerary";

// Send2Coyote web app's Firebase configuration
const firebaseConfig = {
  apiKey: "BALBALABALANAA",
  authDomain: "BALBALABALANAA",
  projectId: "BALBALABALANAA",
  storageBucket: "BALBALABALANAA",
  messagingSenderId: "BALBALABALANAA",
  appId: "BALBALABALANAA",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firestore
const db = getFirestore(app);

// Add Itinerary to Coyote_users in Firestore
export const addItinerary = async (CoyoteId: string, Itinerary: Itinerary): Promise<void> => {
  try {
    const docRef = doc(db, "Coyote_users", CoyoteId);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      try {
        await setDoc(doc(db, "Coyote_users"), {
          id: CoyoteId,
          itineraries: [Itinerary],
        });
        console.log("Add Itinerary: ", Itinerary.id, ", to EXISTING User: ", CoyoteId);
      } catch (e) {
        console.error("Error adding Itinerary ", Itinerary.id, ", to EXISTING User: ", CoyoteId, ", Error: ", e);
      }
    } else {
      try {
        await addDoc(collection(db, "Coyote_users"), {
          id: CoyoteId,
          itineraries: [Itinerary],
        });
        console.log("Add Itinerary: ", Itinerary.id, ", to NEW User: ", CoyoteId);
      } catch (e) {
        console.error("Error adding Itinerary ", Itinerary.id, ", to NEW User: ", CoyoteId, ", Error: ", e);
      }
    }
  } catch (e) {
    console.error("Error getting User ", CoyoteId, ", Error: ", e);
  }
};