2021-05-26 17:24:54 +00:00
|
|
|
import EJSON from 'ejson';
|
|
|
|
import moment from 'moment';
|
|
|
|
import orderBy from 'lodash/orderBy';
|
|
|
|
|
|
|
|
import log from '../../utils/log';
|
|
|
|
import { getMessageById } from '../database/services/Message';
|
2022-03-03 20:25:03 +00:00
|
|
|
import { MessageTypeLoad } from '../../constants/messageTypeLoad';
|
2021-05-26 17:24:54 +00:00
|
|
|
import { generateLoadMoreId } from '../utils';
|
2021-09-13 20:41:05 +00:00
|
|
|
import updateMessages from './updateMessages';
|
2022-03-02 14:18:01 +00:00
|
|
|
import { TMessageModel } from '../../definitions';
|
2022-02-21 18:04:17 +00:00
|
|
|
import RocketChat from '../rocketchat';
|
2021-05-26 17:24:54 +00:00
|
|
|
|
|
|
|
const COUNT = 50;
|
|
|
|
|
2022-02-21 18:04:17 +00:00
|
|
|
interface ILoadNextMessages {
|
|
|
|
rid: string;
|
2022-03-02 14:18:01 +00:00
|
|
|
ts: Date;
|
|
|
|
tmid?: string;
|
2022-02-21 18:04:17 +00:00
|
|
|
loaderItem: TMessageModel;
|
|
|
|
}
|
|
|
|
|
2022-03-02 14:18:01 +00:00
|
|
|
export default function loadNextMessages(args: ILoadNextMessages): Promise<void> {
|
2021-09-13 20:41:05 +00:00
|
|
|
return new Promise(async (resolve, reject) => {
|
2021-05-26 17:24:54 +00:00
|
|
|
try {
|
2022-02-21 18:04:17 +00:00
|
|
|
const data = await RocketChat.methodCallWrapper('loadNextMessages', args.rid, args.ts, COUNT);
|
2021-05-26 17:24:54 +00:00
|
|
|
let messages = EJSON.fromJSONValue(data?.messages);
|
|
|
|
messages = orderBy(messages, 'ts');
|
|
|
|
if (messages?.length) {
|
|
|
|
const lastMessage = messages[messages.length - 1];
|
|
|
|
const lastMessageRecord = await getMessageById(lastMessage._id);
|
|
|
|
if (!lastMessageRecord && messages.length === COUNT) {
|
|
|
|
const loadMoreItem = {
|
|
|
|
_id: generateLoadMoreId(lastMessage._id),
|
|
|
|
rid: lastMessage.rid,
|
|
|
|
tmid: args.tmid,
|
|
|
|
ts: moment(lastMessage.ts).add(1, 'millisecond'),
|
2022-03-03 20:25:03 +00:00
|
|
|
t: MessageTypeLoad.NEXT_CHUNK
|
2021-05-26 17:24:54 +00:00
|
|
|
};
|
|
|
|
messages.push(loadMoreItem);
|
|
|
|
}
|
|
|
|
await updateMessages({ rid: args.rid, update: messages, loaderItem: args.loaderItem });
|
2022-03-02 14:18:01 +00:00
|
|
|
return resolve();
|
2021-05-26 17:24:54 +00:00
|
|
|
}
|
2022-03-02 14:18:01 +00:00
|
|
|
return resolve();
|
2021-05-26 17:24:54 +00:00
|
|
|
} catch (e) {
|
|
|
|
log(e);
|
|
|
|
reject(e);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|