Rocket.Chat.ReactNative/app/lib/methods/loadMissedMessages.js

59 lines
1.5 KiB
JavaScript

import { InteractionManager } from 'react-native';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import log from '../../utils/log';
const getLastUpdate = (rid) => {
const sub = database
.objects('subscriptions')
.filtered('rid == $0', rid)[0];
return sub && new Date(sub.lastOpen).toISOString();
};
async function load({ rid: roomId, lastOpen }) {
let lastUpdate;
if (lastOpen) {
lastUpdate = new Date(lastOpen).toISOString();
} else {
lastUpdate = getLastUpdate(roomId);
}
// RC 0.60.0
const { result } = await this.sdk.get('chat.syncMessages', { roomId, lastUpdate, count: 50 });
return result;
}
export default function loadMissedMessages(...args) {
return new Promise(async(resolve, reject) => {
try {
const data = (await load.call(this, ...args));
if (data) {
if (data.updated && data.updated.length) {
const { updated } = data;
updated.forEach(buildMessage);
InteractionManager.runAfterInteractions(() => {
database.write(() => updated.forEach(message => database.create('messages', message, true)));
resolve(updated);
});
}
if (data.deleted && data.deleted.length) {
const { deleted } = data;
InteractionManager.runAfterInteractions(() => {
database.write(() => {
deleted.forEach((m) => {
const message = database.objects('messages').filtered('_id = $0', m._id);
database.delete(message);
});
});
});
}
}
resolve([]);
} catch (e) {
log('loadMissedMessages', e);
reject(e);
}
});
}