Skip to content

Commit

Permalink
fixed too many req error
Browse files Browse the repository at this point in the history
  • Loading branch information
doljko committed Jun 24, 2024
1 parent a2a2a0c commit a0dea2b
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 76 deletions.
3 changes: 1 addition & 2 deletions src/features/Auth/screens/SignUpScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const SignUpScreen = ({ route }) => {
const [phone, setPhone] = useState(null);
const [error, setError] = useState();
const [isLoading, setIsLoading] = useState(false);
let errorMessage = 'An error occurred';

const saveDriver = () => {
if (!validateInputs()) {
Expand All @@ -46,7 +45,7 @@ const SignUpScreen = ({ route }) => {
setIsLoading(false);
Toast.show({
type: 'error',
text1: errorMessage,
text1: 'error',
});
logError(error);
});
Expand Down
25 changes: 20 additions & 5 deletions src/features/Core/screens/ChatScreen.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { faAngleLeft, faEdit, faPaperPlane, faTrash, faUser } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { useNavigation } from '@react-navigation/native';
import { useDriver, useFleetbase } from 'hooks';
import { useDriver, useFleetbase, useMountedState } from 'hooks';
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Alert, FlatList, Platform, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import FastImage from 'react-native-fast-image';
Expand All @@ -27,6 +27,7 @@ const ChatScreen = ({ route }) => {
const [showUserList, setShowUserList] = useState(false);
const driver = useDriver();
const driverUser = driver[0].attributes.user;
const isMounted = useMountedState();

useEffect(() => {
setChannel(channelProps);
Expand All @@ -40,15 +41,31 @@ const ChatScreen = ({ route }) => {
}, [channel]);

useEffect(() => {
console.log('[channel]', channel);
if (!channel) return;

console.log(`[Connecting to socket on channel chat.${channel.id}]`);
createSocketAndListen(`chat.${channel.id}`, socketEvent => {
// const { event, data } = socketEvent;
console.log('Socket event: ', socketEvent, typeof socketEvent);
const { event, data } = socketEvent;
console.log('Socket event: ', event, data);
return reloadChannel(channel?.id);
switch (event) {
case 'chat.added_participant':
case 'chat.removed_participant':
case 'chat_participant.created':
case 'chat_participant.deleted':
case 'chat_message.created':
case 'chat_log.created':
case 'chat_attachment.created':
case 'chat_receipt.created':
reloadChannel(channel?.id);
break;
}

// return reloadChannel(channel?.id);
});
}, [channel]);
}, [isMounted]);

const parseMessages = messages => {
return messages.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)).flatMap((message, index) => parseMessage(message, index));
Expand Down Expand Up @@ -105,8 +122,6 @@ const ChatScreen = ({ route }) => {
return chatParticipant.user === driverUser;
});

const channelUsers = channel?.participants.map(item => item.id);

const uploadFile = async url => {
try {
const resBase64 = await adapter.post('files/base64', {
Expand Down
6 changes: 3 additions & 3 deletions src/features/Core/screens/MainScreen.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { faCalendarDay, faClipboardList, faFileAlt, faRoute, faUser, faWallet, faTextHeight } from '@fortawesome/free-solid-svg-icons';
import { faCalendarDay, faClipboardList, faCommentDots, faFileAlt, faRoute, faUser, faWallet } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useRoute } from '@react-navigation/native';
Expand All @@ -15,8 +15,8 @@ import { tailwind } from 'tailwind';
import { createNewOrderLocalNotificationObject, getColorCode, listenForOrdersFromSocket, logError } from 'utils';
import { syncDevice } from 'utils/Auth';
import { getCurrentLocation, trackDriver } from 'utils/Geo';
import IssuesScreen from './IssuesScreen';
import ChatsScreen from './ChatsScreen';
import IssuesScreen from './IssuesScreen';

const { addEventListener, removeEventListener } = EventRegister;
const Tab = createBottomTabNavigator();
Expand Down Expand Up @@ -143,7 +143,7 @@ const MainScreen = ({ navigation, route }) => {
icon = faFileAlt;
break;
case 'Chat':
icon = faTextHeight;
icon = faCommentDots;
break;
}
// You can return any component that you like here!
Expand Down
158 changes: 92 additions & 66 deletions src/utils/Helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ export default class HelperUtil {
if (!hostname) {
hostname = HelperUtil.config('SOCKETCLUSTER_HOST', 'socket.fleetbase.io');
}

// IF no port set from instance link use env
if (!port) {
port = HelperUtil.config('SOCKETCLUSTER_PORT', 8000);
Expand All @@ -498,76 +498,104 @@ export default class HelperUtil {
autoReconnect: true,
};

console.log('Using socketcluster config', socketConnectionConfig);

// Create socket connection
const socket = socketClusterClient.create(socketConnectionConfig);

// // Listen for socket connection errors
// (async () => {
// // eslint-disable-next-line no-unused-vars
// for await (let event of socket.listener('error')) {
// console.log('[Socket Error]', event);
// }
// })();

// // Listen for socket connection
// (async () => {
// // eslint-disable-next-line no-unused-vars
// for await (let event of socket.listener('connect')) {
// console.log('[Socket Connected]', event);
// }
// })();

// create channel from channel id
const channel = socket.subscribe(channelId);

// subscribe to channel
await channel.listener('subscribe').once();

const handleAsyncIteration = async asyncIterable => {
console.log('[handleAsyncIteration]');
const iterator = asyncIterable[Symbol.asyncIterator]();

const processNext = async () => {
console.log('[processNext]');
// Handle socket connection errors
const handleSocketErrors = async () => {
const errorIterator = socket.listener('error')[Symbol.asyncIterator]();
const processError = async () => {
try {
const { value, done } = await iterator.next();
console.log('[processNext is done?]', done);
console.log('[processNext has value]', JSON.stringify(value));
if (done) {
// If no more data, exit the function
return;
}

// Process the value
console.log('[processNext has value]', JSON.stringify(value));
if (typeof callback === 'function') {
callback(value);
}

// Recursively process the next item
return processNext();
const { value, done } = await errorIterator.next();
if (done) return;
console.error('[Socket Error]', value);
return processError();
} catch (error) {
console.error('Error during async iteration:', error);
// Optionally, handle the error or re-throw it
// throw error;
console.error('Error during error iteration:', error);
}
};
processError();
};
handleSocketErrors();

// Start processing
return processNext();
// Handle socket connection
const handleSocketConnect = async () => {
const connectIterator = socket.listener('connect')[Symbol.asyncIterator]();
const processConnect = async () => {
try {
const { value, done } = await connectIterator.next();
if (done) return;
console.log('[Socket Connected]', value);
return processConnect();
} catch (error) {
console.error('Error during connect iteration:', error);
}
};
processConnect();
};
handleSocketConnect();

try {
// Create channel from channel id
const channel = socket.subscribe(channelId);

console.log('Channel subscribed!');

// Await subscription confirmation
console.log('Awaiting subscription confirmation...');
await channel.listener('subscribe').once();
console.log('Subscription confirmed!');

console.log('Listening to channel for events now');

const handleAsyncIteration = async asyncIterable => {
console.log('[handleAsyncIteration]');
const iterator = asyncIterable[Symbol.asyncIterator]();
console.log('[iterator]', iterator);

const processNext = async () => {
console.log('[processNext]');
try {
const { value, done } = await iterator.next();
console.log('[processNext done?]', done);
console.log('[processNext value]', JSON.stringify(value));
if (done) {
// If no more data, exit the function
return;
}

// Process the value
console.log('[processNext value]', JSON.stringify(value));
if (typeof callback === 'function') {
callback(value);
}

// Recursively process the next item
return processNext();
} catch (error) {
console.error('Error during async iteration:', error);
// Optionally, handle the error or re-throw it
// throw error;
}
};

(async () => {
await handleAsyncIteration(channel);
})();
// // listen to incoming data with callback
// (async () => {
// for await (let output of channel) {
// if (typeof callback === 'function') {
// callback(output);
// }
// }
// })();
// Start processing
return processNext();
};

// Start handling the async iteration for the channel
(async () => {
try {
await handleAsyncIteration(channel);
} catch (error) {
console.error('Error during async iteration:', error);
}
})();
} catch (error) {
console.error('Error during channel subscription or handling:', error);
}
}

static async listenForOrdersFromSocket(channelId, callback) {
Expand Down Expand Up @@ -654,16 +682,14 @@ export {
isApple,
isArray,
isEmpty,
isFalsy,
isObject,
isLastIndex,
isVoid,
isFalsy, isLastIndex, isObject, isVoid,
listCountries,
listenForOrdersFromSocket,
logError,
mutatePlaces,
stripHtml,
stripIframeTags,
sum,
toBoolean,
toBoolean
};

0 comments on commit a0dea2b

Please sign in to comment.