client/src/sagas/syncSaga.js
author ymh <ymh.work@gmail.com>
Fri, 28 Jul 2017 19:40:35 +0200
changeset 129 d48946d164c6
child 130 78246db1cbac
permissions -rw-r--r--
Add a first version of synchronisation Remove redux-offline dependency make the redux state fully immutable TODO: better error management TODO: make syncronization work automatically

import { put, take, all, select } from 'redux-saga/effects'
import * as types from '../constants/actionTypes';
import { getLastSync } from './selectors';
import moment from 'moment';
import { endSynchronize, updateLastSync } from '../actions/syncActions';
import SessionSynchronizer from './SessionSyncronizer';
import NoteSynchronizer from './NoteSyncronizer';


function* watchSync(context) {
  while (true) {
    yield take(types.SYNC_DO_SYNC);
    const lastSync = yield select(getLastSync);


    //const sessions = yield context.client.get('/api/notes/sessions/', {modified_since: lastSync});
    const nextLastSync = moment().unix()

    // TODO: manage errors
    try {
      const syncObjects = yield context.client.get('/api/notes/sync/', { modified_since: lastSync });

      const sessionSynchronizer = new SessionSynchronizer(syncObjects.sessions, context.client);
      yield sessionSynchronizer.syncObjects();

      const noteSynchronizer = new NoteSynchronizer(syncObjects.notes, context.client);
      yield noteSynchronizer.syncObjects();

      yield put(updateLastSync(nextLastSync));
    } finally {
      yield put(endSynchronize());
    }
  }
}

//--- The root saga
export default function* rootSaga(context) {
  yield all([
    watchSync(context)
  ]);
}