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

View File

@ -6,32 +6,12 @@ import { getUserData } from '@/components/services/securestorage/UserData';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import debounce from 'lodash.debounce';
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;
};
import type { User, Relationship, RelationshipData } from '@/components/Types';
const RequestRelationship: React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => {
const scheme = useColorScheme() ?? 'light';
const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState<UserData[]>([]);
const [searchResults, setSearchResults] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(false);
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)}>
<ThemedText>{item.fullName}</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 * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
type UserData = {
id: number;
appleId: string | null;
appleEmail: string | null;
fullName: string;
pfpURL: string | null;
pushToken: string;
createdAt: Date;
};
import type { User } from '@/components/Types';
type UserInfoProps = {
onProfilePictureUpdate: (url: string) => void;
};
const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => {
const [userData, setUserData] = useState<UserData | null>(null);
const [userData, setUserData] = useState<User | null>(null);
useEffect(() => {
const fetchUserData = async () => {
try {
const data: UserData = await getUserData() as UserData;
const data: User = await getUserData() as User;
setUserData(data);
if (data.pfpURL) {
onProfilePictureUpdate(data.pfpURL);
@ -94,7 +84,7 @@ const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => {
const newPfpURL = responseData.pfpURL;
// Update local state
setUserData(prevData => prevData ? {...prevData, pfpURL: newPfpURL} as UserData : null);
setUserData(prevData => prevData ? {...prevData, pfpURL: newPfpURL} as User : null);
// Update SecureStorage
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