Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions src/api/habits/firebase-mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ import {
updateDoc,
} from 'firebase/firestore';

import { getCurrentUserId } from '@/core/auth';
import { type habitColors } from '@/ui/colors';

import { db } from '../common/firebase';
import { getUserById, type UserIdT } from '../users';
import {
getUserById,
getUserWithRelationshipById,
type UserIdT,
} from '../users';
import {
type DbHabitT,
type DbParticipantT,
Expand All @@ -27,7 +32,9 @@ type ColorName = keyof typeof habitColors;
export const createHabit = async (
habitCreationInfo: HabitCreationT,
): Promise<DbHabitT> => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
const currentUserData = await getUserById(myId);
if (currentUserData == null) throw new Error('User data not found');

const newHabit = {
title: habitCreationInfo.title,
Expand All @@ -39,8 +46,8 @@ export const createHabit = async (
},
participants: {
[myId]: {
displayName: 'Alex Chen', // TODO: Get from auth context
username: 'alexchen',
displayName: currentUserData.displayName,
username: currentUserData.username,
lastActivity: serverTimestamp(),
isOwner: true,
} satisfies Omit<DbParticipantT, 'lastActivity'> & {
Expand Down Expand Up @@ -88,8 +95,8 @@ export const editHabit = async (
};

export const acceptHabitInvite = async (habitId: HabitIdT): Promise<void> => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const me = await getUserById(myId);
const myId = getCurrentUserId();
const me = await getUserWithRelationshipById(myId);
if (!me) throw new Error('User not found');

const habitRef = doc(db, 'habits', habitId);
Expand Down
5 changes: 3 additions & 2 deletions src/api/habits/use-habits.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createQuery } from 'react-query-kit';

import { type UserIdT } from '../users';
import { getCurrentUserId } from '@/core';

import { getHabits } from './firebase-queries';
import { type HabitT } from './types';

Expand All @@ -10,7 +11,7 @@ type Variables = void;
export const useHabits = createQuery<Response, Variables, Error>({
queryKey: ['habits'],
fetcher: async () => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
return await getHabits(myId);
},
});
6 changes: 4 additions & 2 deletions src/api/notifications/firebase-mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
serverTimestamp,
} from 'firebase/firestore';

import { getCurrentUserId } from '@/core';

import { db } from '../common/firebase';
import { type HabitIdT } from '../habits';
import { type UserIdT } from '../users';
Expand All @@ -15,7 +17,7 @@ export const sendHabitInvite = async (
habitId: HabitIdT,
receiverId: UserIdT,
) => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
const notification: Omit<DbHabitNotificationT, 'sentAt'> & {
sentAt: ReturnType<typeof serverTimestamp>;
} = {
Expand All @@ -29,7 +31,7 @@ export const sendHabitInvite = async (
};

export const sendNudge = async (habitId: HabitIdT, receiverId: UserIdT) => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
const notification: Omit<DbHabitNotificationT, 'sentAt'> & {
sentAt: ReturnType<typeof serverTimestamp>;
} = {
Expand Down
5 changes: 3 additions & 2 deletions src/api/notifications/use-notifications.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createQuery } from 'react-query-kit';

import { type UserIdT } from '../users';
import { getCurrentUserId } from '@/core';

import { getNotifications } from './firebase-queries';
import { type FriendNotificationT, type HabitNotificationT } from './types';

Expand All @@ -10,7 +11,7 @@ type Variables = void;
export const useNotifications = createQuery<Response, Variables, Error>({
queryKey: ['notifications'],
fetcher: async () => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
return await getNotifications(myId);
},
});
27 changes: 13 additions & 14 deletions src/api/users/firebase-mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import {
addDoc,
collection,
deleteDoc,
doc,
getDocs,
query,
serverTimestamp,
setDoc,
where,
} from 'firebase/firestore';

import { getCurrentUserId } from '@/core';

import { db } from '../common/firebase';
import { type DbRelationshipT, type UserIdT } from './types';

export const sendFriendRequest = async (userId: UserIdT) => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
await addDoc(collection(db, 'notifications'), {
type: 'friendRequest',
senderId: myId,
Expand All @@ -24,9 +24,11 @@ export const sendFriendRequest = async (userId: UserIdT) => {
};

export const acceptFriendRequest = async (userId: UserIdT) => {
const myId = '1' as UserIdT; // TODO: Get from auth context

const relationship: Omit<DbRelationshipT, 'friendsSince'> & { friendsSince: ReturnType<typeof serverTimestamp> } = {
const myId = getCurrentUserId();

const relationship: Omit<DbRelationshipT, 'friendsSince'> & {
friendsSince: ReturnType<typeof serverTimestamp>;
} = {
status: 'friends',
friendsSince: serverTimestamp(),
};
Expand All @@ -37,7 +39,7 @@ export const acceptFriendRequest = async (userId: UserIdT) => {
userId2: userId,
...relationship,
});

await addDoc(collection(db, 'relationships'), {
userId1: userId,
userId2: myId,
Expand All @@ -46,8 +48,8 @@ export const acceptFriendRequest = async (userId: UserIdT) => {
};

export const removeFriend = async (userId: UserIdT) => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();

// Find and delete both relationship documents
const relationshipsRef = collection(db, 'relationships');
const q1 = query(
Expand All @@ -61,13 +63,10 @@ export const removeFriend = async (userId: UserIdT) => {
where('userId2', '==', myId),
);

const [snapshot1, snapshot2] = await Promise.all([
getDocs(q1),
getDocs(q2),
]);
const [snapshot1, snapshot2] = await Promise.all([getDocs(q1), getDocs(q2)]);

await Promise.all([
...snapshot1.docs.map((doc) => deleteDoc(doc.ref)),
...snapshot2.docs.map((doc) => deleteDoc(doc.ref)),
]);
};
};
29 changes: 22 additions & 7 deletions src/api/users/firebase-queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ import {
type Timestamp,
where,
} from 'firebase/firestore';
import { getDownloadURL, ref } from 'firebase/storage';

import { db } from '../common/firebase';
import { getCurrentUserId } from '@/core';

import { db, storage } from '../common/firebase';
import {
type DbRelationshipT,
type DbUserT,
Expand Down Expand Up @@ -68,13 +71,19 @@ const getRelationshipStatus = async (
return convertDbRelationshipToRelationship(relationship as DbRelationshipT);
};

export const getUserById = async (
export const getUserById = async (id: UserIdT): Promise<UserT | null> => {
const userDoc = await getDoc(doc(db, 'users', id));
if (!userDoc.exists()) return null;
return convertDbUserToUser(id, userDoc.data() as DbUserT);
};

export const getUserWithRelationshipById = async (
id: UserIdT,
): Promise<UserWithRelationshipT | null> => {
const userDoc = await getDoc(doc(db, 'users', id));
if (!userDoc.exists()) return null;

const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
const relationship = await getRelationshipStatus(myId, id);

return {
Expand Down Expand Up @@ -141,9 +150,15 @@ export const searchUsers = async (searchQuery: string): Promise<UserT[]> => {
};

export const getUserPicture = async (userId: UserIdT): Promise<string> => {
const pictureDoc = await getDoc(doc(db, 'pictures', userId));
if (!pictureDoc.exists()) throw new Error('User picture not found');
return pictureDoc.data().url;
const defaultProfilePic = require('/assets/images/default_profile_pic.png');
try {
const pictureRef = ref(storage, `profilePics/${userId}`);
const url = await getDownloadURL(pictureRef);
return url;
} catch (error) {
console.log(`No profile image found for ${userId}, using default.`);
return defaultProfilePic;
}
};

export const getFriends = async (userId: UserIdT): Promise<UserT[]> => {
Expand Down Expand Up @@ -177,7 +192,7 @@ export const getFriends = async (userId: UserIdT): Promise<UserT[]> => {
// Fetch user data for each friend
const friends = await Promise.all(
uniqueFriendIds.map(async (friendId) => {
const friend = await getUserById(friendId as UserIdT);
const friend = await getUserWithRelationshipById(friendId as UserIdT);
if (!friend) throw new Error('Friend not found');
return friend;
}),
Expand Down
6 changes: 4 additions & 2 deletions src/api/users/use-friends.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { createQuery } from 'react-query-kit';

import { getCurrentUserId } from '@/core';

import { getFriends } from './firebase-queries';
import { type UserIdT, type UserWithRelationshipT } from './types';
import { type UserWithRelationshipT } from './types';

type Response = UserWithRelationshipT[];
type Variables = void;
Expand All @@ -10,7 +12,7 @@ type Variables = void;
export const useFriends = createQuery<Response, Variables, Error>({
queryKey: ['friends'],
fetcher: async () => {
const myId = '1' as UserIdT; // TODO: Get from auth context
const myId = getCurrentUserId();
const friends = await getFriends(myId);
return friends.map((friend) => ({
...friend,
Expand Down
4 changes: 2 additions & 2 deletions src/api/users/use-remove-friend.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createMutation } from 'react-query-kit';

import { queryClient } from '../common';
import { removeFriend } from './firebase-mutations';
import { getUserById } from './firebase-queries';
import { getUserWithRelationshipById } from './firebase-queries';
import { type UserIdT, type UserT } from './types';

type Variables = { id: UserIdT };
Expand All @@ -11,7 +11,7 @@ type Response = UserT;
export const useRemoveFriend = createMutation<Response, Variables, Error>({
mutationFn: async (variables) => {
await removeFriend(variables.id);
const user = await getUserById(variables.id);
const user = await getUserWithRelationshipById(variables.id);
if (!user) throw new Error('User not found');
return user;
},
Expand Down
4 changes: 2 additions & 2 deletions src/api/users/use-send-friend-request.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createMutation } from 'react-query-kit';

import { queryClient } from '../common';
import { sendFriendRequest } from './firebase-mutations';
import { getUserById } from './firebase-queries';
import { getUserWithRelationshipById } from './firebase-queries';
import { type UserIdT, type UserT } from './types';

type Variables = { id: UserIdT };
Expand All @@ -11,7 +11,7 @@ type Response = UserT;
export const useSendFriendRequest = createMutation<Response, Variables, Error>({
mutationFn: async (variables) => {
await sendFriendRequest(variables.id);
const user = await getUserById(variables.id);
const user = await getUserWithRelationshipById(variables.id);
if (!user) throw new Error('User not found');
return user;
},
Expand Down
4 changes: 2 additions & 2 deletions src/api/users/use-user.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createQuery } from 'react-query-kit';

import { getUserById } from './firebase-queries';
import { getUserWithRelationshipById } from './firebase-queries';
import { type UserIdT, type UserWithRelationshipT } from './types';

type Variables = { id: UserIdT };
Expand All @@ -9,7 +9,7 @@ type Response = UserWithRelationshipT;
export const useUser = createQuery<Response, Variables, Error>({
queryKey: ['user'],
fetcher: async (variables) => {
const user = await getUserById(variables.id);
const user = await getUserWithRelationshipById(variables.id);
if (!user) throw new Error('User not found');
return user;
},
Expand Down
Loading