just another day

This commit is contained in:
Gabriel Brown 2024-10-25 16:57:25 -05:00
parent 0e46c630a6
commit e84597883b
11 changed files with 882 additions and 1401 deletions

View File

@ -10,7 +10,7 @@ const TabLayout = () => {
<Tabs <Tabs
screenOptions={{ screenOptions={{
tabBarActiveTintColor: Colors[scheme].tint, tabBarActiveTintColor: Colors[scheme].tint,
//headerShown: false headerShown: false,
headerStyle: { headerStyle: {
backgroundColor: Colors[scheme].background, backgroundColor: Colors[scheme].background,
}, },
@ -37,6 +37,7 @@ const TabLayout = () => {
<Tabs.Screen <Tabs.Screen
name='messages' name='messages'
options={{ options={{
headerShown: true,
title: 'Messages', title: 'Messages',
tabBarIcon: ({ color, focused }) => ( tabBarIcon: ({ color, focused }) => (
<TabBarIcon name={focused ? 'chatbubbles' : 'chatbubbles-outline'} color={color} /> <TabBarIcon name={focused ? 'chatbubbles' : 'chatbubbles-outline'} color={color} />

View File

@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useReducer, useState, useRef } from 'react'; import React, { useCallback, useEffect, useReducer, useState } from 'react';
import { io } from 'socket.io-client'; import { io } from 'socket.io-client';
import { ThemedText, ThemedView } from '@/components/theme/Theme'; import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { Alert, Linking, Platform, StyleSheet, ActivityIndicator } from 'react-native'; import { Alert, Linking, Platform, StyleSheet } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons'; import { MaterialIcons } from '@expo/vector-icons';
import { import {
GiftedChat, GiftedChat,
@ -11,7 +11,6 @@ import {
SystemMessage, SystemMessage,
} from 'react-native-gifted-chat'; } from 'react-native-gifted-chat';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import AccessoryBar from '@/components/chat/AccessoryBar';
import CustomActions from '@/components/chat/CustomActions'; import CustomActions from '@/components/chat/CustomActions';
import CustomView from '@/components/chat/CustomView'; import CustomView from '@/components/chat/CustomView';
import * as Clipboard from 'expo-clipboard'; import * as Clipboard from 'expo-clipboard';
@ -93,44 +92,34 @@ const MessagesScreen = () => {
} catch (error) { } catch (error) {
console.error('Error initializing users:', error); console.error('Error initializing users:', error);
Alert.alert('Error', 'Failed to initialize users. Please try again.'); Alert.alert('Error', 'Failed to initialize users. Please try again.');
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: [] });
} }
}; };
initialize(); initialize();
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!user || !partner) return; if (!user || !partner) {
console.log('User or partner not found');
return;
}
const socket = io(process.env.EXPO_PUBLIC_WEBSOCKET_URL as string, { const socket = io(process.env.EXPO_PUBLIC_WEBSOCKET_URL as string, {
transports: ['websocket'], transports: ['websocket'],
}); });
socket.on('connect', () => { socket.on('connect', () => {
//console.log('Connected to WebSocket server'); console.log('Connected to WebSocket server');
socket.emit('join', user.id); socket.emit('join', user.id);
}); });
socket.on('connect_error', (error) => { socket.on('connect_error', (error) => {
console.error('Error connecting to WebSocket server:', error); console.error('Error connecting to WebSocket server:', error);
}); });
socket.on('message', async (newMessage) => { socket.on('message', async (newMessage) => {
console.log('New message received:', newMessage); const initialMessages = await getMessages(user.id, 20, 0);
const formattedMessage = formatMessages([newMessage]); if (!initialMessages) return;
const formattedMessages = formatMessages(initialMessages);
dispatch({ dispatch({
type: ActionKind.SEND_MESSAGE, type: ActionKind.SEND_MESSAGE,
payload: GiftedChat.append(state.messages, formattedMessage), payload: formattedMessages,
}); });
if (user && partner) {
dispatch({ type: ActionKind.LOAD_EARLIER_START });
const initialMessages = await getMessages(user.id, 20, 0);
console.log('initial messages: ', initialMessages);
if (initialMessages) {
const formattedMessages = formatMessages(initialMessages);
console.log('formatted messages: ', formattedMessages);
dispatch({
type: ActionKind.LOAD_EARLIER_MESSAGES,
payload: formattedMessages,
});
}
} else console.log('user or partner not initialized');
}); });
return () => { return () => {
socket.disconnect(); socket.disconnect();
@ -141,7 +130,7 @@ const MessagesScreen = () => {
const fetchMessages = async () => { const fetchMessages = async () => {
if (user && partner) { if (user && partner) {
dispatch({ type: ActionKind.LOAD_EARLIER_START }); dispatch({ type: ActionKind.LOAD_EARLIER_START });
const initialMessages = await getMessages(user.id, 20, 0); const initialMessages = await getMessages(user.id);
if (initialMessages) { if (initialMessages) {
const formattedMessages = formatMessages(initialMessages); const formattedMessages = formatMessages(initialMessages);
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: formattedMessages }); dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: formattedMessages });
@ -189,8 +178,7 @@ const MessagesScreen = () => {
message: messageToSend, message: messageToSend,
}, },
}; };
//sendPushNotification(partner.pushToken, notificationMessage); sendPushNotification(partner.pushToken, notificationMessage);
sendPushNotification(user.pushToken, notificationMessage);
// Add the message with a tempId immediately to the state // Add the message with a tempId immediately to the state
const tempFormattedMessages = formatMessages([messageToSend]); const tempFormattedMessages = formatMessages([messageToSend]);
@ -203,9 +191,12 @@ const MessagesScreen = () => {
try { try {
// Send the message to the server // Send the message to the server
const sentMessage = await sendMessage(messageToSend); const sentMessage = await sendMessage(messageToSend);
if (!user || isNaN(user.id)) {
console.error('User not found');
throw new Error('User not found');
}
// Fetch the latest messages from the server to ensure consistency // Fetch the latest messages from the server to ensure consistency
const updatedMessages = await getMessages(user?.id ?? 0); const updatedMessages = await getMessages(user.id);
if (updatedMessages) { if (updatedMessages) {
const formattedMessages = formatMessages(updatedMessages); const formattedMessages = formatMessages(updatedMessages);
dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages }); dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
@ -311,15 +302,6 @@ const MessagesScreen = () => {
dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping }); dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping });
}, [dispatch]); }, [dispatch]);
const renderAccessory = useCallback(() => {
return (
<AccessoryBar
onSend={onSend}
isTyping={() => setIsTyping(!state.isTyping)}
/>
);
}, [onSend, setIsTyping, state.isTyping]);
const renderCustomActions = useCallback( const renderCustomActions = useCallback(
props => props =>
Platform.OS === 'web' ? null : ( Platform.OS === 'web' ? null : (
@ -374,7 +356,6 @@ const MessagesScreen = () => {
fontWeight: '200', fontWeight: '200',
}} }}
renderQuickReplySend={renderQuickReplySend} renderQuickReplySend={renderQuickReplySend}
renderAccessory={renderAccessory}
renderActions={renderCustomActions} renderActions={renderCustomActions}
renderSystemMessage={renderSystemMessage} renderSystemMessage={renderSystemMessage}
renderCustomView={renderCustomView} renderCustomView={renderCustomView}

View File

@ -1,129 +0,0 @@
export default () => [
{
_id: Math.round(Math.random() * 1000000),
text:
'It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text:
'It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text:
'It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text:
'It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'React Native lets you build mobile apps using only JavaScript',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: Math.round(Math.random() * 1000000),
text: 'This is a system message.',
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
system: true,
},
]

View File

@ -1,168 +0,0 @@
export default [
{
_id: 9,
text: '#awesome 3',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 8,
text: '#awesome 2',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 7,
text: '#awesome',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 6,
text: 'Paris',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
},
image:
'https://www.xtrafondos.com/wallpapers/torre-eiffel-en-paris-415.jpg',
sent: true,
received: true,
},
{
_id: 5,
text: 'Send me a picture!',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 4,
text: '',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
},
sent: true,
received: true,
location: {
latitude: 48.864601,
longitude: 2.398704,
},
},
{
_id: 3,
text: 'Where are you?',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 2,
text: 'Yes, and I use #GiftedChat!',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
},
sent: true,
received: true,
},
{
_id: 1,
text: 'Are you building a chat app?',
createdAt: new Date(),
user: {
_id: 1,
name: 'Developer',
},
},
{
_id: 10,
text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
createdAt: new Date(),
quickReplies: {
type: 'radio', // or 'checkbox',
keepIt: true,
values: [
{
title: '😋 Yes',
value: 'yes',
},
{
title:
'📷 Yes, let me show you with a picture! Again let me show you with a picture!',
value: 'yes_picture',
},
{
title: '😞 Nope. What?',
value: 'no',
},
],
},
user: {
_id: 2,
name: 'React Native',
},
},
{
_id: 20,
text: 'This is a quick reply. Do you love Gifted Chat? (checkbox)',
createdAt: new Date(),
quickReplies: {
type: 'checkbox', // or 'checkbox',
values: [
{
title: 'Yes',
value: 'yes',
},
{
title: 'Yes, let me show you with a picture!',
value: 'yes_picture',
},
{
title: 'Nope. What?',
value: 'no',
},
],
},
user: {
_id: 2,
name: 'React Native',
},
},
{
_id: 30,
createdAt: new Date(),
video: 'https://media.giphy.com/media/3o6ZthZjk09Xx4ktZ6/giphy.mp4',
user: {
_id: 2,
name: 'React Native',
},
},
{
_id: 31,
createdAt: new Date(),
audio:
'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3',
user: {
_id: 2,
name: 'React Native',
},
},
]

View File

@ -1,264 +0,0 @@
import React, { useCallback, useReducer } from 'react';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { Alert, Linking, Platform, StyleSheet } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import {
GiftedChat,
IMessage,
Send,
SendProps,
SystemMessage,
} from 'react-native-gifted-chat';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import AccessoryBar from '@/components/chat/AccessoryBar';
import CustomActions from '@/components/chat/CustomActions';
import CustomView from '@/components/chat/CustomView';
//import NavBar from '@/components/chat/NavBar';
import earlierMessages from '@/components/chat/data/earlierMessages';
import messages from '@/components/chat/data/messages';
import * as Clipboard from 'expo-clipboard';
import {
GCUser,
GCState,
GCStateAction,
ActionKind,
} from '@/constants/Types';
import {getInitialMessages, sendMessage} from '@/constants/APIs';
const tempUser: GCUser = {
_id: 1,
name: 'Developer',
};
const reducer = (state: GCState, action: GCStateAction) => {
switch (action.type) {
case ActionKind.SEND_MESSAGE: {
return {
...state,
step: state.step + 1,
messages: action.payload,
};
}
case ActionKind.LOAD_EARLIER_MESSAGES: {
return {
...state,
loadEarlier: true,
isLoadingEarlier: false,
messages: action.payload,
};
}
case ActionKind.LOAD_EARLIER_START: {
return {
...state,
isLoadingEarlier: true,
}
}
case ActionKind.SET_IS_TYPING: {
return {
...state,
isTyping: action.payload,
}
}
}
};
const MessagesScreen = () => {
//const newMessages =
const [state, dispatch] = useReducer(reducer, {
messages: messages,
step: 0,
loadEarlier: true,
isLoadingEarlier: false,
isTyping: false,
})
const onSend = useCallback((messages: any[]) => {
const sentMessages = [{ ...messages[0], sent: true, received: true }]
const newMessages = GiftedChat.append(
state.messages, sentMessages, Platform.OS !== 'web'
);
dispatch({ type: ActionKind.SEND_MESSAGE, payload: newMessages });
}, [dispatch, state.messages]);
const onLoadEarlier = useCallback(() => {
dispatch({ type: ActionKind.LOAD_EARLIER_START });
setTimeout(() => {
const newMessages = GiftedChat.prepend(
state.messages, earlierMessages() as IMessage[], Platform.OS !== 'web'
);
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: newMessages })
}, 1500) // simulating network
}, [dispatch, state.messages]);
const parsePatterns = useCallback(() => {
return [
{
pattern: /#(\w+)/g,
style: { textDecorationLine: 'underline', color: 'darkorange' },
onPress: () => Linking.openURL('https://www.gbrown.org'),
},
]
}, []);
const onLongPressAvatar = useCallback((pressedUser: any) => {
Alert.alert(JSON.stringify(pressedUser))
}, []);
const onPressAvatar = useCallback(() => {
Alert.alert('Pressed avatar!')
}, []);
const handleLongPress = useCallback((context: unknown, currentMessage: object) => {
if (!currentMessage.text) return;
const options = [
'Copy text',
'Cancel',
]
const cancelButtonIndex = options.length - 1;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(context as any).actionSheet().showActionSheetWithOptions(
{ options, cancelButtonIndex },
(buttonIndex: number) => {
switch (buttonIndex) {
case 0:
Clipboard.setStringAsync(currentMessage.text);
break;
default: break;
}
}
)
}, []);
const onQuickReply = useCallback((replies: any[]) => {
const createdAt = new Date();
if (replies.length === 1)
onSend([
{
createdAt,
_id: Math.round(Math.random() * 1000000),
text: replies[0].title,
tempUser,
},
]);
else if (replies.length > 1)
onSend([
{
createdAt,
_id: Math.round(Math.random() * 1000000),
text: replies.map(reply => reply.title).join(', '),
tempUser,
},
]);
else console.warn('replies param is not set correctly');
}, []);
const renderQuickReplySend = useCallback(() => {
return <ThemedText>{'custom send =>'}</ThemedText>
}, []);
const setIsTyping = useCallback((isTyping: boolean) => {
dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping });
}, [dispatch]);
const onSendFromUser = useCallback((messages: IMessage[] = []) => {
const createdAt = new Date();
const messagesToUpload = messages.map(message => ({
...message, tempUser, createdAt, id: Math.round(Math.random() * 1000000),
}));
onSend(messagesToUpload);
}, [onSend]);
const renderAccessory = useCallback(() => {
return (
<AccessoryBar
onSend={onSendFromUser}
isTyping={() => setIsTyping(!state.isTyping)}
/>
);
}, [onSendFromUser, setIsTyping, state.isTyping]);
const renderCustomActions = useCallback(
props =>
Platform.OS === 'web' ? null : (
<CustomActions {...props} onSend={onSendFromUser} />
),
[onSendFromUser]
);
const renderSystemMessage = useCallback(props => {
return (
<SystemMessage
{...props}
containerStyle={{marginBottom: 15}}
textStyle={{fontSize: 14}}
/>
);
}, []);
const renderCustomView = useCallback(props => {
return <CustomView {...props} />
}, []);
const renderSend = useCallback((props: SendProps<IMessage>) => {
return (
<Send
{...props}
containerStyle={{justifyContent: 'center', paddingHorizontal: 10}}
>
<MaterialIcons size={30} color={'tomato'} name={'send'} />
</Send>
);
}, []);
return (
<SafeAreaView style={styles.fill}>
<ThemedView style={styles.fill}>
<GiftedChat
messages={state.messages}
onSend={onSend}
loadEarlier={state.loadEarlier}
onLoadEarlier={onLoadEarlier}
isLoadingEarlier={state.isLoadingEarlier}
parsePatterns={parsePatterns}
user={tempUser}
scrollToBottom
onPressAvatar={onPressAvatar}
onLongPressAvatar={onLongPressAvatar}
onLongPress={handleLongPress}
onQuickReply={onQuickReply}
quickReplyStyle={{ borderRadius: 2 }}
quickReplyTextStyle={{
fontWeight: '200',
}}
renderQuickReplySend={renderQuickReplySend}
//renderAccessory={renderAccessory}
renderActions={renderCustomActions}
renderSystemMessage={renderSystemMessage}
renderCustomView={renderCustomView}
renderSend={renderSend}
keyboardShouldPersistTaps='never'
timeTextStyle={{
left: { color: 'red' },
right: { color: 'yellow' },
}}
isTyping={state.isTyping}
inverted={Platform.OS !== 'web'}
infiniteScroll
/>
</ThemedView>
</SafeAreaView>
)
};
const ChatWrapper = () => {
return (
<SafeAreaProvider><MessagesScreen /></SafeAreaProvider>
);
};
export default ChatWrapper;
const styles = StyleSheet.create({
fill: {
flex: 1,
},
});

View File

@ -0,0 +1,7 @@
import React, { useEffect, useState } from 'react';
import { StyleSheet, ActivityIndicator, TouchableOpacity } from 'react-native';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { SafeAreaView } from 'react-native-safe-area-context';

View File

@ -92,6 +92,7 @@ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
alignItems: 'center', alignItems: 'center',
marginTop: 40,
}, },
profileContainer: { profileContainer: {
alignItems: 'center', alignItems: 'center',

View File

@ -36,7 +36,6 @@ export const sendPushNotification = async(expoPushToken: string | null, notifica
body: JSON.stringify(message), body: JSON.stringify(message),
}); });
const result = await response.json(); const result = await response.json();
console.log('Push notification sent:', result);
} catch (error) { } catch (error) {
console.error('Error sending push notification:', error); console.error('Error sending push notification:', error);
Alert.alert('Error', 'Failed to send push notification.'); Alert.alert('Error', 'Failed to send push notification.');

View File

@ -1,14 +1,18 @@
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
import type { User, RelationshipData, Message } from '@/constants/Types'; import type { User, RelationshipData, Message, Countdown } from '@/constants/Types';
const API_KEY = process.env.EXPO_PUBLIC_API_KEY ?? '';
const API_URL = process.env.EXPO_PUBLIC_API_URL ?? '';
export const getInitialDataByAppleId = async (appleId: string) => { export const getInitialDataByAppleId = async (appleId: string) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/users/getInitialDataByAppleId`; const apiUrl = `${API_URL}/api/users/getInitialDataByAppleId`;
const response = await fetch((apiUrl + `?appleId=${appleId}`), { const response = await fetch((apiUrl + `?appleId=${appleId}`), {
method: 'GET', method: 'GET',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
}); });
return response; return response;
@ -21,12 +25,12 @@ export const getInitialDataByAppleId = async (appleId: string) => {
export const createUser = export const createUser =
async (appleId: string, email: string, fullName: string, pushToken: string) => { async (appleId: string, email: string, fullName: string, pushToken: string) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/users/createUser`; const apiUrl = `${API_URL}/api/users/createUser`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
body: JSON.stringify({ body: JSON.stringify({
appleId: appleId, appleId: appleId,
@ -50,12 +54,12 @@ export const createUser =
export const updatePushToken = async (userId: number, pushToken: string) => { export const updatePushToken = async (userId: number, pushToken: string) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/users/updatePushToken`; const apiUrl = `${API_URL}/api/users/updatePushToken`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
body: JSON.stringify({ body: JSON.stringify({
userId: userId, userId: userId,
@ -76,14 +80,14 @@ export const updatePushToken = async (userId: number, pushToken: string) => {
export const updateProfilePicture = async (userId: number, pfpUrl: string) => { export const updateProfilePicture = async (userId: number, pfpUrl: string) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/users/updatePfp`; const apiUrl = `${API_URL}/api/users/updatePfp`;
const response = await FileSystem.uploadAsync(apiUrl, pfpUrl, { const response = await FileSystem.uploadAsync(apiUrl, pfpUrl, {
fieldName: 'file', fieldName: 'file',
httpMethod: 'POST', httpMethod: 'POST',
uploadType: FileSystem.FileSystemUploadType.MULTIPART, uploadType: FileSystem.FileSystemUploadType.MULTIPART,
parameters: { userId: userId.toString() }, parameters: { userId: userId.toString() },
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
}); });
if (response.status !== 200) if (response.status !== 200)
@ -100,10 +104,10 @@ export const updateProfilePicture = async (userId: number, pfpUrl: string) => {
export const checkRelationshipStatus = async (userId: number) => { export const checkRelationshipStatus = async (userId: number) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/relationships/checkStatus`; const apiUrl = `${API_URL}/api/relationships/checkStatus`;
const response = await fetch((apiUrl + `?userId=${userId}`), { const response = await fetch((apiUrl + `?userId=${userId}`), {
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
}); });
if (!response.ok) { if (!response.ok) {
@ -121,12 +125,12 @@ export const checkRelationshipStatus = async (userId: number) => {
export const updateRelationshipStatus = async (userId: number, status: 'accepted' | 'rejected') => { export const updateRelationshipStatus = async (userId: number, status: 'accepted' | 'rejected') => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/relationships/updateStatus`; const apiUrl = `${API_URL}/api/relationships/updateStatus`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
body: JSON.stringify({ body: JSON.stringify({
userId: userId, userId: userId,
@ -151,10 +155,10 @@ export const updateRelationshipStatus = async (userId: number, status: 'accepted
export const searchUsers = async (userId: number, searchTerm: string) => { export const searchUsers = async (userId: number, searchTerm: string) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/users/search`; const apiUrl = `${API_URL}/api/users/search`;
const response = await fetch((apiUrl + `?userId=${userId}&searchTerm=${searchTerm}`), { const response = await fetch((apiUrl + `?userId=${userId}&searchTerm=${searchTerm}`), {
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
}); });
if (!response.ok) { if (!response.ok) {
@ -173,12 +177,12 @@ export const searchUsers = async (userId: number, searchTerm: string) => {
export const sendRelationshipRequest = async (userId: number, targetUserId: number) => { export const sendRelationshipRequest = async (userId: number, targetUserId: number) => {
if (!userId || !targetUserId || isNaN(userId) || isNaN(targetUserId)) return; if (!userId || !targetUserId || isNaN(userId) || isNaN(targetUserId)) return;
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/relationships/createRequest`; const apiUrl = `${API_URL}/api/relationships/createRequest`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
body: JSON.stringify({ userId: userId, targetUserId: targetUserId }), body: JSON.stringify({ userId: userId, targetUserId: targetUserId }),
}); });
@ -198,10 +202,10 @@ export const sendRelationshipRequest = async (userId: number, targetUserId: numb
export const getMessages = async (userId: number, limit: number = 20, offset: number = 0) => { export const getMessages = async (userId: number, limit: number = 20, offset: number = 0) => {
if (!userId || isNaN(userId)) return; if (!userId || isNaN(userId)) return;
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/get`; const apiUrl = `${API_URL}/api/messages/get`;
const response = await fetch((apiUrl+`?userId=${userId}&limit=${limit}&offset=${offset}`), { const response = await fetch((apiUrl+`?userId=${userId}&limit=${limit}&offset=${offset}`), {
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
}); });
if (!response.ok) { if (!response.ok) {
@ -219,12 +223,12 @@ export const getMessages = async (userId: number, limit: number = 20, offset: nu
export const sendMessage = async (message: Message) => { export const sendMessage = async (message: Message) => {
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/send`; const apiUrl = `${API_URL}/api/messages/send`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': API_KEY,
}, },
body: JSON.stringify({ body: JSON.stringify({
message: message, message: message,
@ -242,3 +246,51 @@ export const sendMessage = async (message: Message) => {
throw error; throw error;
} }
}; };
export const setCountdown = async (userId: number, countdown: Countdown ) => {
try {
const apiUrl = `${API_URL}/api/relationships/countdown/set`;
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY,
},
body: JSON.stringify({
userId: userId,
countdown: countdown,
}),
});
if (!response.ok) {
throw new Error(
`Error setting countdown: ${response.status} ${response.statusText}`
);
}
const countdownData = await response.json() as Countdown;
return countdownData;
} catch (error: unknown) {
console.error('Error setting countdown:', error);
throw error;
}
};
export const getCountdown = async (userId: number) => {
try {
const apiUrl = `${API_URL}/api/relationships/countdown/get`;
const response = await fetch((apiUrl + `?userId=${userId}`), {
headers: {
'x-api-key': API_KEY,
},
});
if (!response.ok) {
throw new Error(
`Error getting countdown: ${response.status} ${response.statusText}`
);
}
const countdownData = await response.json() as Countdown;
return countdownData;
} catch (error: unknown) {
console.error('Error getting countdown:', error);
throw error;
}
};

View File

@ -49,11 +49,11 @@
"react-native-safe-area-context": "4.10.5", "react-native-safe-area-context": "4.10.5",
"react-native-screens": "3.31.1", "react-native-screens": "3.31.1",
"react-native-web": "~0.19.13", "react-native-web": "~0.19.13",
"socket.io-client": "^4.8.0" "socket.io-client": "^4.8.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.25.9", "@babel/core": "^7.26.0",
"@types/jest": "^29.5.13", "@types/jest": "^29.5.14",
"@types/react": "~18.2.79", "@types/react": "~18.2.79",
"@types/react-test-renderer": "^18.3.0", "@types/react-test-renderer": "^18.3.0",
"jest": "^29.7.0", "jest": "^29.7.0",

1555
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff