Rocket.Chat.ReactNative/app/sagas/rooms.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-02-27 20:29:37 +00:00
import {
put, select, race, take, fork, cancel, takeLatest
2019-02-27 20:29:37 +00:00
} from 'redux-saga/effects';
import { BACKGROUND } from 'redux-enhancer-react-native-appstate';
2017-08-17 02:06:22 +00:00
import * as types from '../actions/actionsTypes';
import { roomsSuccess, roomsFailure } from '../actions/rooms';
import database from '../lib/realm';
import log from '../utils/log';
import mergeSubscriptionsRooms from '../lib/methods/helpers/mergeSubscriptionsRooms';
2019-02-27 20:29:37 +00:00
import RocketChat from '../lib/rocketchat';
let roomsSub;
const removeSub = function removeSub() {
if (roomsSub && roomsSub.stop) {
roomsSub.stop();
}
};
const handleRoomsRequest = function* handleRoomsRequest() {
try {
removeSub();
roomsSub = yield RocketChat.subscribeRooms();
2019-02-27 20:29:37 +00:00
const newRoomsUpdatedAt = new Date();
const server = yield select(state => state.server.server);
const [serverRecord] = database.databases.serversDB.objects('servers').filtered('id = $0', server);
const { roomsUpdatedAt } = serverRecord;
const [subscriptionsResult, roomsResult] = yield RocketChat.getRooms(roomsUpdatedAt);
const { subscriptions } = mergeSubscriptionsRooms(subscriptionsResult, roomsResult);
database.write(() => {
subscriptions.forEach((subscription) => {
try {
database.create('subscriptions', subscription, true);
} catch (error) {
2019-05-28 16:18:46 +00:00
log('err_rooms_request_create_sub', error);
}
});
});
2019-02-27 20:29:37 +00:00
database.databases.serversDB.write(() => {
try {
database.databases.serversDB.create('servers', { id: server, roomsUpdatedAt: newRoomsUpdatedAt }, true);
} catch (e) {
2019-05-28 16:18:46 +00:00
log('err_rooms_request_update', e);
2019-02-27 20:29:37 +00:00
}
});
yield put(roomsSuccess());
} catch (e) {
yield put(roomsFailure(e));
2019-05-28 16:18:46 +00:00
log('err_rooms_request', e);
}
};
const handleLogout = function handleLogout() {
removeSub();
};
const root = function* root() {
yield takeLatest(types.LOGOUT, handleLogout);
while (true) {
const params = yield take(types.ROOMS.REQUEST);
const roomsRequestTask = yield fork(handleRoomsRequest, params);
yield race({
serverReq: take(types.SERVER.SELECT_REQUEST),
background: take(BACKGROUND),
logout: take(types.LOGOUT)
});
yield cancel(roomsRequestTask);
}
};
export default root;