mirror of
https://github.com/urosran/cally.git
synced 2025-07-10 07:07:16 +00:00
87 lines
3.4 KiB
TypeScript
87 lines
3.4 KiB
TypeScript
import {useQuery} from "react-query";
|
|
import firestore from "@react-native-firebase/firestore";
|
|
import {useAuthContext} from "@/contexts/AuthContext";
|
|
import {useAtomValue} from "jotai";
|
|
import {isFamilyViewAtom} from "@/components/pages/calendar/atoms";
|
|
import {colorMap} from "@/constants/colorMap";
|
|
|
|
export const useGetEvents = () => {
|
|
const {user, profileData} = useAuthContext();
|
|
const isFamilyView = useAtomValue(isFamilyViewAtom);
|
|
|
|
return useQuery({
|
|
queryKey: ["events", user?.uid, isFamilyView],
|
|
queryFn: async () => {
|
|
const db = firestore();
|
|
|
|
const userId = user?.uid;
|
|
const familyId = profileData?.familyId;
|
|
let allEvents = [];
|
|
|
|
if (isFamilyView) {
|
|
const familyQuery = db.collection("Events").where("familyID", "==", familyId);
|
|
const creatorQuery = db.collection("Events").where("creatorId", "==", userId);
|
|
const attendeeQuery = db.collection("Events").where("attendees", "array-contains", userId);
|
|
|
|
const [familySnapshot, creatorSnapshot, attendeeSnapshot] = await Promise.all([
|
|
familyQuery.get(),
|
|
creatorQuery.get(),
|
|
attendeeQuery.get(),
|
|
]);
|
|
|
|
const familyEvents = familySnapshot.docs.map(doc => doc.data());
|
|
const creatorEvents = creatorSnapshot.docs.map(doc => doc.data());
|
|
const attendeeEvents = attendeeSnapshot.docs.map(doc => doc.data());
|
|
|
|
allEvents = [...familyEvents, ...creatorEvents, ...attendeeEvents];
|
|
} else {
|
|
const creatorQuery = db.collection("Events").where("creatorId", "==", userId);
|
|
const attendeeQuery = db.collection("Events").where("attendees", "array-contains", userId);
|
|
|
|
const [creatorSnapshot, attendeeSnapshot] = await Promise.all([
|
|
creatorQuery.get(),
|
|
attendeeQuery.get(),
|
|
]);
|
|
|
|
const creatorEvents = creatorSnapshot.docs.map(doc => doc.data());
|
|
const attendeeEvents = attendeeSnapshot.docs.map(doc => doc.data());
|
|
|
|
allEvents = [...creatorEvents, ...attendeeEvents];
|
|
}
|
|
|
|
allEvents = allEvents.filter((event, index, self) =>
|
|
index === self.findIndex(e => e.id === event.id)
|
|
);
|
|
|
|
allEvents = allEvents.filter(event => {
|
|
if (event.private) {
|
|
return event.creatorId === userId;
|
|
}
|
|
return true;
|
|
});
|
|
|
|
return await Promise.all(
|
|
allEvents.map(async (event) => {
|
|
const profileSnapshot = await db
|
|
.collection("Profiles")
|
|
.doc(event.creatorId)
|
|
.get();
|
|
|
|
const profileData = profileSnapshot.data();
|
|
const eventColor = profileData?.eventColor || colorMap.pink;
|
|
|
|
return {
|
|
id: event.id,
|
|
title: event.title,
|
|
start: new Date(event.startDate.seconds * 1000),
|
|
end: new Date(event.endDate.seconds * 1000),
|
|
hideHours: event.allDay,
|
|
eventColor: eventColor,
|
|
};
|
|
})
|
|
);
|
|
},
|
|
staleTime: Infinity,
|
|
cacheTime: Infinity,
|
|
});
|
|
}; |