verdnatura-chat/app/lib/methods/loadThreadMessages.js

51 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-04-17 17:01:03 +00:00
import { InteractionManager } from 'react-native';
import EJSON from 'ejson';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import log from '../../utils/log';
async function load({ tmid, offset }) {
2019-04-17 17:01:03 +00:00
try {
// RC 1.0
const result = await this.sdk.get('chat.getThreadMessages', {
tmid, count: 50, offset, sort: { ts: -1 }, query: { _hidden: { $ne: true } }
});
if (!result || !result.success) {
2019-04-17 17:01:03 +00:00
return [];
}
return result.messages;
2019-04-17 17:01:03 +00:00
} catch (error) {
console.log(error);
return [];
}
}
export default function loadThreadMessages({ tmid, offset = 0 }) {
2019-04-17 17:01:03 +00:00
return new Promise(async(resolve, reject) => {
try {
const data = await load.call(this, { tmid, offset });
2019-04-17 17:01:03 +00:00
if (data && data.length) {
InteractionManager.runAfterInteractions(() => {
database.write(() => data.forEach((m) => {
try {
const message = buildMessage(EJSON.fromJSONValue(m));
message.rid = tmid;
database.create('threadMessages', message, true);
} catch (e) {
2019-05-28 16:18:46 +00:00
log('err_load_thread_messages_create', e);
2019-04-17 17:01:03 +00:00
}
}));
return resolve(data);
});
} else {
return resolve([]);
}
} catch (e) {
2019-05-28 16:18:46 +00:00
log('err_load_thread_messages', e);
2019-04-17 17:01:03 +00:00
reject(e);
}
});
}