2021-02-09 04:00:18 +08:00
|
|
|
import { useContext, useEffect } from 'react';
|
|
|
|
import _ from 'lodash';
|
2021-01-20 01:06:32 +08:00
|
|
|
import { ChatContext, ACTIONS } from './context';
|
|
|
|
import { UsersContext } from '../users-context/context';
|
|
|
|
import ChatLogger from '/imports/ui/components/chat/chat-logger/ChatLogger';
|
|
|
|
|
|
|
|
let usersData = {};
|
2021-02-09 04:00:18 +08:00
|
|
|
let messageQueue = [];
|
2021-01-20 01:06:32 +08:00
|
|
|
const Adapter = () => {
|
|
|
|
const usingChatContext = useContext(ChatContext);
|
|
|
|
const { dispatch } = usingChatContext;
|
|
|
|
const usingUsersContext = useContext(UsersContext);
|
|
|
|
const { users } = usingUsersContext;
|
|
|
|
ChatLogger.trace('chatAdapter::body::users', users);
|
2021-02-09 04:00:18 +08:00
|
|
|
|
2021-01-20 01:06:32 +08:00
|
|
|
useEffect(() => {
|
|
|
|
usersData = users;
|
|
|
|
}, [usingUsersContext]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
// TODO: hadle removed Messages
|
|
|
|
// TODO: listen to websocket message to avoid full list comparsion
|
2021-02-09 04:00:18 +08:00
|
|
|
const throttledDispatch = _.throttle(() => {
|
|
|
|
const dispatchedMessageQueue = [...messageQueue];
|
|
|
|
messageQueue = [];
|
|
|
|
dispatch({
|
|
|
|
type: ACTIONS.ADDED,
|
|
|
|
value: dispatchedMessageQueue,
|
|
|
|
});
|
|
|
|
}, 1000, { trailing: true, leading: true });
|
|
|
|
|
2021-02-04 04:49:58 +08:00
|
|
|
Meteor.connection._stream.socket.addEventListener('message', (msg) => {
|
|
|
|
if (msg.data.indexOf('{"msg":"added","collection":"group-chat-msg"') != -1) {
|
|
|
|
const parsedMsg = JSON.parse(msg.data);
|
|
|
|
if (parsedMsg.msg === 'added') {
|
2021-02-09 04:00:18 +08:00
|
|
|
messageQueue.push({
|
|
|
|
msg: parsedMsg.fields,
|
|
|
|
senderData: usersData[parsedMsg.fields.sender.id],
|
|
|
|
});
|
|
|
|
throttledDispatch();
|
2021-02-04 04:49:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2021-01-20 01:06:32 +08:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Adapter;
|