Skip to content

Commit

Permalink
Putting all API calls into one file for readability, testability, and…
Browse files Browse the repository at this point in the history
… comprehension
  • Loading branch information
rhit-villencr committed Jan 15, 2025
1 parent ad63bf8 commit 068c243
Show file tree
Hide file tree
Showing 18 changed files with 84 additions and 86 deletions.
2 changes: 1 addition & 1 deletion app/accountSetting.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useCallback, useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
import { cLog } from './log';
import { cLog } from '../components/log';
import { useFocusEffect } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

Expand Down
4 changes: 2 additions & 2 deletions app/addCalendarEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { calendarFields, IPAddr } from '@/constants/constants';
import { calendarFields } from '@/constants/constants';
import GenericAddViewPageForm from './genericAddViewEventPage';

export default function AddCalendarEvents() {
Expand All @@ -18,7 +18,7 @@ export default function AddCalendarEvents() {
initialData={calendarInitialData}
fields={calendarFields}
mainPage="mainCalendarEvents"
updateEndpoint={`${IPAddr}/add_calendar_event`}
updateEndpoint={`/add_calendar_event`}
method="POST"
/>
);
Expand Down
4 changes: 2 additions & 2 deletions app/addFinanceEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { financeFields, IPAddr } from '@/constants/constants';
import { financeFields } from '@/constants/constants';
import GenericAddViewPageForm from './genericAddViewEventPage';

export default function AddFinanceEvents() {
Expand All @@ -18,7 +18,7 @@ export default function AddFinanceEvents() {
initialData={financeInitialData}
fields={financeFields}
mainPage='mainFinanceTracker'
updateEndpoint={`${IPAddr}/add_finance_events`}
updateEndpoint={`/add_finance_events`}
method="POST"
/>
);
Expand Down
4 changes: 2 additions & 2 deletions app/addHealthEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { healthFields, IPAddr } from '@/constants/constants';
import { healthFields } from '@/constants/constants';
import GenericAddViewPageForm from './genericAddViewEventPage';

export default function AddHealthEvents() {
Expand All @@ -17,7 +17,7 @@ export default function AddHealthEvents() {
initialData={healthInitialData}
fields={healthFields}
mainPage='mainHealthTracker'
updateEndpoint={`${IPAddr}/add_health_events`}
updateEndpoint={`/add_health_events`}
method="POST"
/>
);
Expand Down
8 changes: 4 additions & 4 deletions app/addMeals.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react'
import { mealFields, IPAddr } from '@/constants/constants';
import { mealFields } from '@/constants/constants';
import GenericAddViewPageForm from './genericAddViewEventPage';

export default function AddMeals() {
Expand All @@ -16,8 +16,8 @@ export default function AddMeals() {
initialData={mealInitialData}
fields={mealFields}
mainPage="mainMealTracker"
updateEndpoint={`${IPAddr}/add_meal_events`}
fetchEndpoint={`${IPAddr}/get_ingredients`}
updateEndpoint={`/add_meal_events`}
fetchEndpoint={`/get_ingredients`}
keyValue={{'key':"id", "value":"ingredientName"}}
method="POST"
/>
Expand All @@ -32,4 +32,4 @@ export default function AddMeals() {
// console.error('Error adding new ingredient:', error);
// }
// };

15 changes: 5 additions & 10 deletions app/genericAddViewEventPage.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import React, { useCallback, useState } from 'react';
import axios from 'axios';
import DateTimePicker from '@react-native-community/datetimepicker';
import { View, Text, TextInput, ScrollView, TouchableOpacity } from 'react-native';
import { Dropdown } from 'react-native-element-dropdown';
import { cLog } from './log';
import { cLog } from '../components/log';
import { styles } from '@/assets/styles/styles';
import { GenericEventPageProps, RootStackParamList } from '@/components/Types';
import { StackNavigationProp } from '@react-navigation/stack';
import { useNavigation, useFocusEffect, RouteProp, useRoute } from '@react-navigation/native';
import MultiSelect from 'react-native-multiple-select';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { verifyToken } from '@/constants/constants';
import { call } from '../components/apiCall';

const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initialData = {}, fields, mainPage, updateEndpoint, fetchEndpoint, keyValue, method }) => {
const [showDatePicker, setShowDatePicker] = useState(false);
Expand Down Expand Up @@ -46,13 +46,8 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
cLog(formattedData);
try {
cLog('Saving event to:' + updateEndpoint);
if (method === 'PUT') {
const response = await axios.put(updateEndpoint, formattedData);
cLog('Event updated successfully:' + response.data);
} else {
const response = await axios.post(updateEndpoint, formattedData);
cLog('Event saved successfully:' + response.data);
}
const response = await call(updateEndpoint, method, undefined, formattedData)
cLog('Event updated successfully:' + response.data);
} catch (error) {
console.error('Error saving event:', error);
}
Expand Down Expand Up @@ -87,7 +82,7 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
if (!fetchEndpoint) return;
try {
const userId = await AsyncStorage.getItem('userId');
const response = await axios.get(`${fetchEndpoint}/${userId}`);
const response = await call(`${fetchEndpoint}/${userId}`, 'GET');
const formattedData = response.data.map((item: { [x: string]: any; id: any; name: any; }) => ({
value: keyValue ? item[keyValue.key] : item.id,
label: keyValue ? item[keyValue.value] : item.name,
Expand Down
16 changes: 4 additions & 12 deletions app/genericMainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { Ionicons } from "@expo/vector-icons";
import { EventProps, GoogleCalendarProps, NavigationProps, RootStackParamList, Task } from '@/components/Types';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { cLog } from './log';
import { formatTime, getPageFromEventType, getPageName, IPAddr, verifyToken } from '@/constants/constants';
import axios from 'axios';
import { cLog } from '../components/log';
import { formatTime, getPageFromEventType, getPageName, verifyToken } from '@/constants/constants';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { call } from '../components/apiCall';

interface FormProps extends EventProps, GoogleCalendarProps, NavigationProps {
title: string;
Expand Down Expand Up @@ -77,22 +77,14 @@ const GenericMainPageForm: React.FC<FormProps> = ({
const fetchEvents = async () => {
try {
const userId = await AsyncStorage.getItem('userId');
const hit = `${IPAddr}${hitAddress}${userId}`;
cLog(`Fetching events from: ${hit}`);

const response = await axios.get(hit);
const response = await call(`${hitAddress}${userId}`, 'GET');

if (response.status === 200 && response.data) {
const { events, googleCalendarLinked } = response.data;
cLog(`response.data:`);
cLog(response.data);
cLog(`events:`);
cLog(events);

if (googleCalendar) {
setIsGoogleCalendarLinked(googleCalendarLinked);
}

const eventsArray = Array.isArray(events) ? events : response.data;
cLog(`eventsArray:`);
cLog(eventsArray);
Expand Down
13 changes: 6 additions & 7 deletions app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import React, { useState, useCallback, useRef } from 'react';
import { IPAddr } from '@/constants/constants';
import { RootStackParamList, UserInfo } from '@/components/Types';
import axios from 'axios';
import { styles } from '@/assets/styles/styles';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { cLog } from './log';
import { cLog } from '../components/log';
import AsyncStorage from "@react-native-async-storage/async-storage";
import { StackNavigationProp } from '@react-navigation/stack';
import { TextInput, View, Text, TouchableOpacity } from 'react-native';
import { call } from '../components/apiCall';

export default function TaskScreen() {
type Prop = StackNavigationProp<RootStackParamList, keyof RootStackParamList>;
Expand Down Expand Up @@ -40,7 +39,7 @@ export default function TaskScreen() {

const performLoginRequest = async (url: string, data: object) => {
try {
const response = await axios.put(url, data);
const response = await call(url, 'PUT', undefined, data);
cLog('Login response:', response.data);
await handleLoginResponse(response.data);
} catch (error) {
Expand All @@ -51,16 +50,16 @@ export default function TaskScreen() {
const checkLogin = async () => {
const [storedToken, storedUserName] = await AsyncStorage.multiGet(['token', 'userName']);
if (storedToken[1] && storedUserName[1]) {
await performLoginRequest(`${IPAddr}/checkLogin`, { userName: storedUserName[1], token: storedToken[1] });
await performLoginRequest(`/checkLogin`, { userName: storedUserName[1], token: storedToken[1] });
} else {
console.log('No valid token or username found');
cLog('No valid token or username found');
}
};

const handleLogin = async () => {
cLog("Attempting to log in...");
const { userName, password } = credentials;
performLoginRequest(`${IPAddr}/login`, { userName, password })
performLoginRequest(`/login`, { userName, password })
}

const parseUserInfo = (data: string): UserInfo => {
Expand Down
18 changes: 4 additions & 14 deletions app/mainCalendarEvents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import GenericMainPageForm from './genericMainPage';
import { Alert } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
import axios from 'axios';
import { IPAddr } from '@/constants/constants';
import { cLog } from './log'
import { cLog } from '../components/log'
import { call } from '../components/apiCall';

const CLIENT_ID = process.env.EXPO_PUBLIC_CLIENT_ID || '';
const CLIENT_SECRET = process.env.EXPO_PUBLIC_CLIENT_SECRET || '';
Expand Down Expand Up @@ -52,11 +51,7 @@ export default function CalendarTracker() {
params.append('client_secret', CLIENT_SECRET);
params.append('redirect_uri', REDIRECT_URI);
params.append('grant_type', 'authorization_code');
const response = await axios.post(TOKEN_URI, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const response = await call(TOKEN_URI, 'POST', 'application/x-www-form-urlencoded', params);
if (response.data.access_token) {
cLog("Received access token:" + response.data.access_token);
linkGoogleCalendar(1, response.data.access_token);
Expand All @@ -73,12 +68,7 @@ export default function CalendarTracker() {
const linkGoogleCalendar = async (userId: any, token: any) => {
cLog("Linking Google Calendar for user and fetching events...");
try {
const hit = `${IPAddr}/link_calendar`;
cLog("Linking Google Calendar with hit:" + hit);
const response = await axios.post(hit, {
userId: userId,
accessToken: token,
});
const response = await call(`/link_calendar`, 'POST', undefined, { userId, accessToken: token });
if (response.status === 200 && response.data.includes("successfully")) {
cLog('Google Calendar linked successfully:' + response.data);
Alert.alert('Google Calendar linked successfully!');
Expand Down
37 changes: 20 additions & 17 deletions app/notes.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import React, { useCallback, useState } from 'react';
import { View, Text, TextInput, TouchableOpacity } from 'react-native';
import { cLog } from './log';
import { IPAddr } from '@/constants/constants';
import { cLog } from '../components/log';
import { styles } from '@/assets/styles/styles';
import axios from 'axios';
import { useFocusEffect } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { call } from '../components/apiCall';

export default function Notes() {
const initialData = { userId: 1, text: "" };
Expand All @@ -20,10 +19,8 @@ export default function Notes() {
event_date: currentDate,
event_time: currentTime,
};
const hit = IPAddr + '/add_note';
const response = await axios.put(hit, updatedFormData);

console.log('Note saved successfully: ' + response.data);
const response = await call('/add_note', 'PUT', undefined, updatedFormData);
cLog('Note saved successfully: ' + response.data);
} catch (error) {
console.error('Error saving note:', error);
}
Expand All @@ -34,16 +31,22 @@ export default function Notes() {
};

const fetchNote = async () => {
const hit = IPAddr + '/get_note/' + (await AsyncStorage.getItem('userId'));
cLog('Fetching note from:' + hit);
axios.get(hit)
.then(response => {
const events = response.data.map((event: { text: any; }) => ({
text: `${event.text}`,
}));
setFormData({ ...formData, text: events[0]?.text || "" });
})
.catch(error => console.error('Error fetching events:', error));
try {
const userId = await AsyncStorage.getItem('userId');
if (!userId) throw new Error('User ID not found');

const hit = '/get_note/' + userId;
cLog('Fetching note from: ' + hit);

const response = await call(hit, 'GET');
const events = response.data.map((event: { text: any; }) => ({
text: `${event.text}`,
}));

setFormData({ ...formData, text: events[0]?.text || "" });
} catch (error) {
console.error('Error fetching note:', error);
}
};

useFocusEffect(
Expand Down
4 changes: 2 additions & 2 deletions app/viewCalendarEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React from 'react';
import GenericAddViewEventForm from './genericAddViewEventPage';
import { IPAddr, calendarFields } from '@/constants/constants';
import { calendarFields } from '@/constants/constants';

export default function ViewCalendarEvents() {
return (
<GenericAddViewEventForm
title="Calendar event"
fields={calendarFields}
updateEndpoint={`${IPAddr}/update_calendar_event`}
updateEndpoint={`/update_calendar_event`}
mainPage="mainCalendarEvents"
method="PUT"
/>
Expand Down
4 changes: 2 additions & 2 deletions app/viewFinanceEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React from 'react';
import GenericAddViewEventForm from './genericAddViewEventPage';
import { IPAddr, financeFields } from '@/constants/constants';
import { financeFields } from '@/constants/constants';

export default function ViewFinanceEvents() {
return (
<GenericAddViewEventForm
title="Finance Event"
fields={financeFields}
updateEndpoint={`${IPAddr}/update_finance_event`}
updateEndpoint={`/update_finance_event`}
mainPage="mainFinanceTracker"
method="PUT"
/>
Expand Down
4 changes: 2 additions & 2 deletions app/viewHealthEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React from 'react';
import GenericAddViewEventForm from './genericAddViewEventPage';
import { IPAddr, healthFields } from '@/constants/constants';
import { healthFields } from '@/constants/constants';

export default function ViewHealthEvents() {
return (
<GenericAddViewEventForm
title="Health Event"
fields={healthFields}
updateEndpoint={`${IPAddr}/update_health_event`}
updateEndpoint={`/update_health_event`}
mainPage="mainHealthTracker"
method="PUT"
/>
Expand Down
6 changes: 3 additions & 3 deletions app/viewMealEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import React from 'react';
import GenericAddViewEventForm from './genericAddViewEventPage';
import { IPAddr, mealFields } from '@/constants/constants';
import { mealFields } from '@/constants/constants';

export default function ViewMealEvents() {
return (
<GenericAddViewEventForm
title="Meal Event"
fields={mealFields}
updateEndpoint={`${IPAddr}/update_meal_event`}
fetchEndpoint={`${IPAddr}/get_ingredients`}
updateEndpoint={`/update_meal_event`}
fetchEndpoint={`/get_ingredients`}
mainPage="mainMealTracker"
keyValue={{ 'key': "id", "value": "ingredientName" }}
method="PUT"
Expand Down
Binary file modified backend/omniplanner.db
Binary file not shown.
21 changes: 21 additions & 0 deletions components/apiCall.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { IPAddr } from '@/constants/constants';
import axios, { AxiosResponse } from 'axios';
import { cLog } from './log';

export const call = async (endpoint: string, method: string, headers?: string, data?: any): Promise<AxiosResponse<any>> => {
const fullUrl = `${IPAddr}${endpoint}`;
cLog('Full URL:', fullUrl);

try {
const response = await axios({
url: fullUrl,
method: method,
data: data,
headers: headers ? { 'Content-Type': headers } : {},
});
return response;
} catch (error) {
console.error('API call error:', error);
throw error;
}
};
File renamed without changes.
Loading

0 comments on commit 068c243

Please sign in to comment.