Move types. I need to rewrite this app

This commit is contained in:
Gabriel Brown 2024-10-14 13:48:22 -05:00
parent fc1975fd74
commit f96076d5ae
7 changed files with 120 additions and 124 deletions

0
assets/fonts/SpaceMono-Regular.ttf Normal file → Executable file
View File

21
components/Types.tsx Normal file
View File

@ -0,0 +1,21 @@
export type User = {
id: number;
appleId: string | null;
appleEmail: string | null;
fullName: string;
pfpURL: string | null;
pushToken: string;
createdAt: Date;
};
export type Relationship = {
id: number;
title: string;
status: 'pending' | 'accepted' | 'rejected';
relationshipStartDate: Date;
createdAt: Date;
};
export type RelationshipData = {
relationship: Relationship;
partner: User;
};

View File

@ -3,34 +3,15 @@ import { Image, StyleSheet, AppState } from 'react-native';
import { ThemedView } from '@/components/ThemedView'; import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText'; import { ThemedText } from '@/components/ThemedText';
import { getUserData } from '@/components/services/securestorage/UserData'; import { getUserData } from '@/components/services/securestorage/UserData';
import { saveRelationshipData, getRelationshipData } from '@/components/services/securestorage/RelationshipData'; import {
saveRelationshipData,
getRelationshipData
} from '@/components/services/securestorage/RelationshipData';
import Button from '@/components/buttons/Button'; import Button from '@/components/buttons/Button';
import { Colors } from '@/constants/Colors'; import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme'; import { useColorScheme } from '@/hooks/useColorScheme';
import RequestRelationship from '@/components/home/RequestRelationship'; import RequestRelationship from '@/components/home/RequestRelationship';
import type { User, Relationship, RelationshipData } from '@/components/Types';
type UserData = {
id: number;
appleId: string | null;
appleEmail: string | null;
fullName: string;
pfpURL: string | null;
pushToken: string;
createdAt: Date;
};
type Relationship = {
id: number;
title: string;
status: 'pending' | 'accepted' | 'rejected';
relationshipStartDate: Date;
createdAt: Date;
};
type RelationshipData = {
relationship: Relationship;
partner: UserData;
};
type RelationshipProps = { type RelationshipProps = {
profilePictureUrl: string | null; profilePictureUrl: string | null;
@ -39,32 +20,33 @@ type RelationshipProps = {
const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => { const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
const scheme = useColorScheme() ?? 'light'; const scheme = useColorScheme() ?? 'light';
const [status, setStatus] = useState<RelationshipData | null>(null); const [status, setStatus] = useState<RelationshipData | null>(null);
const [userData, setUserData] = useState<UserData | null>(null); const [user, setUser] = useState<User | null>(null);
const [showRequestRelationship, setShowRequestRelationship] = useState(false); const [showRequestRelationship, setShowRequestRelationship] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const handleRequestSent = (data: RelationshipData) => {
setStatus(data);
setShowRequestRelationship(false);
};
useEffect(() => { useEffect(() => {
fetchRelationshipStatus(); fetchRelationshipStatus();
setupPeriodicCheck(); setupPeriodicCheck();
}, []); }, []);
useEffect(() => { useEffect(() => {
if (profilePictureUrl && userData) { if (profilePictureUrl && user) {
setUserData(prevData => prevData ? {...prevData, pfpURL: profilePictureUrl} : null); setUser(prevUserData =>
prevUserData ? {...prevUserData, pfpURL: profilePictureUrl} : null);
} }
}, [profilePictureUrl]); }, [profilePictureUrl]);
const handleRequestSent = (data: RelationshipData) => {
setStatus(data);
setShowRequestRelationship(false);
}
const setupPeriodicCheck = () => { const setupPeriodicCheck = () => {
let intervalId: NodeJS.Timeout | null = null; let intervalId: NodeJS.Timeout | null = null;
const startChecking = () => { const startChecking = () => {
checkRelationshipStatus(); checkRelationshipStatus();
intervalId = setInterval(checkRelationshipStatus, 600000); // intervalId = setInterval(checkRelationshipStatus, 60000);
}; };
const stopChecking = () => { const stopChecking = () => {
@ -75,44 +57,32 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
}; };
const handleAppStateChange = (nextAppState: string) => { const handleAppStateChange = (nextAppState: string) => {
if (nextAppState === 'active') { if (nextAppState === 'active') startChecking();
startChecking(); else stopChecking();
} else {
stopChecking();
}
}; };
const subscription = AppState.addEventListener('change', handleAppStateChange); const subscription = AppState.addEventListener('change', handleAppStateChange);
if (AppState.currentState === 'active') startChecking();
if (AppState.currentState === 'active') {
startChecking();
}
return () => { return () => {
stopChecking(); stopChecking();
subscription.remove(); subscription.remove();
}; }
}; };
const fetchRelationshipStatus = async () => { const fetchRelationshipStatus = async () => {
setLoading(true); setLoading(true);
try { try {
const userDataFromStorage: UserData = await getUserData() as UserData; const userFromStorage: User = await getUserData() as User;
if (!userDataFromStorage || !userDataFromStorage.id) { if (!userFromStorage || !userFromStorage.id)
throw new Error('User data not found'); throw new Error("User or user data not found");
} setUser(userFromStorage);
setUserData(userDataFromStorage);
// First, try to get relationship data from SecureStore
const storedRelationshipData = await getRelationshipData(); const storedRelationshipData = await getRelationshipData();
if (storedRelationshipData) { if (storedRelationshipData)
setStatus(storedRelationshipData); setStatus(storedRelationshipData);
}
// Then, fetch the latest data from the API
await checkRelationshipStatus(); await checkRelationshipStatus();
} catch (error) { } catch (error) {
console.log('Error fetching relationship status:', error); console.log('Error fetching relationship status:', error)
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -120,20 +90,22 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
const checkRelationshipStatus = async () => { const checkRelationshipStatus = async () => {
try { try {
const userDataFromStorage: UserData = await getUserData() as UserData; const userFromStorage: User = await getUserData() as User;
if (!userDataFromStorage || !userDataFromStorage.id) { if (!userFromStorage || !userFromStorage.id)
throw new Error('User data not found'); throw new Error("User or user data not found");
} const response = await fetch(
`${process.env.EXPO_PUBLIC_API_URL}/relationships/getRelationshipData` +
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/relationships/getRelationshipData?userId=${userDataFromStorage.id}`, { `?userId=${userFromStorage.id}`, {
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
}, },
}); });
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
throw new Error(errorData.message || `HTTP error! status: ${response.status}`); throw new Error(
errorData.message ||
`HTTP error! status: ${response.status}`
);
} }
const data = await response.json() as RelationshipData; const data = await response.json() as RelationshipData;
setStatus(data); setStatus(data);
@ -142,16 +114,19 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
console.log('No relationship found or error checking status:', error); console.log('No relationship found or error checking status:', error);
setStatus(null); setStatus(null);
} finally { } finally {
setLoading(false);
} }
}; };
const handleUpdateRelationshipStatus = async (newStatus: 'accepted' | 'rejected') => { const handleUpdateRelationshipStatus =
async (newStatus: 'accepted' | 'rejected') => {
if (!status || !status.relationship) { if (!status || !status.relationship) {
console.error('No relationship to update'); console.error('No relationship to update');
return; return;
} }
try { try {
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/relationships/updateStatus`, { const response = await fetch(
`${process.env.EXPO_PUBLIC_API_URL}/relationships/updateStatus`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -162,19 +137,16 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
status: newStatus, status: newStatus,
}), }),
}); });
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
throw new Error(errorData.message || `HTTP error! status: ${response.status}`); throw new Error(
errorData.message ||
`HTTP error! status: ${response.status}`
);
} }
const result = await response.json(); const result = await response.json();
if (result) { if (result) await checkRelationshipStatus();
// Refresh the relationship status else throw new Error('Failed to update relationship status');
await checkRelationshipStatus();
} else {
throw new Error('Failed to update relationship status');
}
} catch (error) { } catch (error) {
console.error('Error updating relationship status:', error); console.error('Error updating relationship status:', error);
} }
@ -186,14 +158,23 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
if (loading) { if (loading) {
return <ThemedText>Loading...</ThemedText>; return <ThemedText>Loading...</ThemedText>;
} }
const renderRelationshipContent = () => { const renderRelationshipContent = () => {
if (!status || !status.relationship) { if (!status || !status.relationship) {
// Case 1: Not in a relationship // Case 1: Not in a relationship
return showRequestRelationship ? ( return showRequestRelationship ? (
<RequestRelationship onRequestSent={handleRequestSent} /> <RequestRelationship onRequestSent={handleRequestSent} />
) : ( ) : (
<Button width={220} height={60} onPress={() => setShowRequestRelationship(true)}> <Button
<ThemedText style={[styles.buttonLabel, {color: Colors[scheme].background}]}> width={220} height={60}
onPress={() => setShowRequestRelationship(true)}
>
<ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
Request Relationship Request Relationship
</ThemedText> </ThemedText>
</Button> </Button>
@ -202,24 +183,41 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
// Case 2 & 3: Pending relationship (we can't differentiate who requested it) // Case 2 & 3: Pending relationship (we can't differentiate who requested it)
return ( return (
<> <>
<ThemedText style={styles.title}>Pending Relationship</ThemedText> <ThemedText style={styles.title}>
Pending Relationship
</ThemedText>
<ThemedView style={styles.profileContainer}> <ThemedView style={styles.profileContainer}>
<ThemedView style={styles.profileWrapper}> <ThemedView style={styles.profileWrapper}>
<Image <Image
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${status.partner.pfpURL}` }} source={{
uri: `${process.env.EXPO_PUBLIC_URL}` +
`${status.partner.pfpURL}`
}}
style={styles.profilePicture} style={styles.profilePicture}
/> />
<ThemedText style={styles.name}>{status.partner.fullName}</ThemedText> <ThemedText style={styles.name}>
{status.partner.fullName}
</ThemedText>
</ThemedView> </ThemedView>
</ThemedView> </ThemedView>
<ThemedView style={styles.buttonContainer}> <ThemedView style={styles.buttonContainer}>
<Button width={100} height={40} onPress={handleAcceptRequest}> <Button width={100} height={40} onPress={handleAcceptRequest}>
<ThemedText style={[styles.buttonLabel, {color: Colors[scheme].background}]}> <ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
Accept Accept
</ThemedText> </ThemedText>
</Button> </Button>
<Button width={100} height={40} onPress={handleRejectRequest}> <Button width={100} height={40} onPress={handleRejectRequest}>
<ThemedText style={[styles.buttonLabel, {color: Colors[scheme].background}]}> <ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
Reject Reject
</ThemedText> </ThemedText>
</Button> </Button>
@ -230,24 +228,31 @@ const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
// Case 4: In an accepted relationship // Case 4: In an accepted relationship
return ( return (
<> <>
<ThemedText style={styles.title}>{status.relationship.title}</ThemedText> <ThemedText style={styles.title}>
{status.relationship.title}
</ThemedText>
<ThemedView style={styles.profileContainer}> <ThemedView style={styles.profileContainer}>
{userData && ( {user && (
<ThemedView style={styles.profileWrapper}> <ThemedView style={styles.profileWrapper}>
<Image <Image
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${userData.pfpURL}` }} source={{ uri: `${process.env.EXPO_PUBLIC_URL}${user.pfpURL}` }}
style={styles.profilePicture} style={styles.profilePicture}
/> />
<ThemedText style={styles.name}>{userData.fullName.split(' ')[0]}</ThemedText> <ThemedText style={styles.name}>
{user.fullName.split(' ')[0]}
</ThemedText>
</ThemedView> </ThemedView>
)} )}
{status.partner && ( {status.partner && (
<ThemedView style={styles.profileWrapper}> <ThemedView style={styles.profileWrapper}>
<Image <Image
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${status.partner.pfpURL}` }} source={{ uri: `${process.env.EXPO_PUBLIC_URL}` +
`${status.partner.pfpURL}` }}
style={styles.profilePicture} style={styles.profilePicture}
/> />
<ThemedText style={styles.name}>{status.partner.fullName.split(' ')[0]}</ThemedText> <ThemedText style={styles.name}>
{status.partner.fullName.split(' ')[0]}
</ThemedText>
</ThemedView> </ThemedView>
)} )}
</ThemedView> </ThemedView>

View File

@ -6,32 +6,12 @@ import { getUserData } from '@/components/services/securestorage/UserData';
import { Colors } from '@/constants/Colors'; import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme'; import { useColorScheme } from '@/hooks/useColorScheme';
import debounce from 'lodash.debounce'; import debounce from 'lodash.debounce';
import type { User, Relationship, RelationshipData } from '@/components/Types';
type UserData = {
id: number;
appleId: string | null;
appleEmail: string | null;
fullName: string;
pfpURL: string | null;
pushToken: string;
createdAt: Date;
};
type RelationshipData = {
relationship: {
id: number;
title: string;
status: "pending" | "accepted" | "rejected";
relationshipStartDate: Date;
createdAt: Date;
};
partner: UserData;
};
const RequestRelationship: React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => { const RequestRelationship: React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => {
const scheme = useColorScheme() ?? 'light'; const scheme = useColorScheme() ?? 'light';
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState<UserData[]>([]); const [searchResults, setSearchResults] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [currentUserId, setCurrentUserId] = useState<number | null>(null); const [currentUserId, setCurrentUserId] = useState<number | null>(null);
@ -94,7 +74,7 @@ const RequestRelationship: React.FC<{ onRequestSent: (data: RelationshipData) =>
} }
}; };
const renderUserItem = ({ item }: { item: UserData }) => ( const renderUserItem = ({ item }: { item: User }) => (
<TouchableOpacity style={styles.userItem} onPress={() => sendRequest(item.id)}> <TouchableOpacity style={styles.userItem} onPress={() => sendRequest(item.id)}>
<ThemedText>{item.fullName}</ThemedText> <ThemedText>{item.fullName}</ThemedText>
<ThemedText>{item.appleEmail}</ThemedText> <ThemedText>{item.appleEmail}</ThemedText>

View File

@ -6,29 +6,19 @@ import { getUserData, updateUserData } from "@/components/services/securestorage
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator'; import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
import * as ImagePicker from 'expo-image-picker'; import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
import type { User } from '@/components/Types';
type UserData = {
id: number;
appleId: string | null;
appleEmail: string | null;
fullName: string;
pfpURL: string | null;
pushToken: string;
createdAt: Date;
};
type UserInfoProps = { type UserInfoProps = {
onProfilePictureUpdate: (url: string) => void; onProfilePictureUpdate: (url: string) => void;
}; };
const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => { const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => {
const [userData, setUserData] = useState<UserData | null>(null); const [userData, setUserData] = useState<User | null>(null);
useEffect(() => { useEffect(() => {
const fetchUserData = async () => { const fetchUserData = async () => {
try { try {
const data: UserData = await getUserData() as UserData; const data: User = await getUserData() as User;
setUserData(data); setUserData(data);
if (data.pfpURL) { if (data.pfpURL) {
onProfilePictureUpdate(data.pfpURL); onProfilePictureUpdate(data.pfpURL);
@ -94,7 +84,7 @@ const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => {
const newPfpURL = responseData.pfpURL; const newPfpURL = responseData.pfpURL;
// Update local state // Update local state
setUserData(prevData => prevData ? {...prevData, pfpURL: newPfpURL} as UserData : null); setUserData(prevData => prevData ? {...prevData, pfpURL: newPfpURL} as User : null);
// Update SecureStorage // Update SecureStorage
await updateUserData({ pfpURL: newPfpURL }); await updateUserData({ pfpURL: newPfpURL });

0
example/assets/fonts/SpaceMono-Regular.ttf Normal file → Executable file
View File

0
example/scripts/reset-project.js Normal file → Executable file
View File