client/src/sagas/index.js
changeset 29 4cfeabef7d5e
child 30 4d93f4ed95bc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/src/sagas/index.js	Mon Jun 12 18:12:38 2017 +0200
@@ -0,0 +1,77 @@
+import PouchDB from 'pouchdb'
+import { put, takeLatest, all } from 'redux-saga/effects'
+import * as types from '../constants/actionTypes';
+import PouchDBFind from 'pouchdb-find';
+import Immutable from 'immutable';
+
+PouchDB.debug.disable();
+PouchDB.plugin(PouchDBFind);
+
+const sessionsDB = new PouchDB('sessions');
+const notesDB = new PouchDB('notes');
+notesDB.createIndex({
+  index: { fields: ['session'] }
+});
+
+// ---
+
+export function* loadSessions() {
+  const response = yield sessionsDB.allDocs({ include_docs: true })
+  const sessions = response.rows.map(row => row.doc)
+  yield put({ type: types.LOAD_SESSIONS, sessions: Immutable.List(sessions) })
+}
+
+export function* watchLoadSessions() {
+  yield takeLatest(types.LOAD_SESSIONS_ASYNC, loadSessions)
+}
+
+// ---
+
+export function* createSession(action) {
+  const response = yield sessionsDB.put(action.session);
+  // TODO Error control
+  const session = Object.assign({}, action.session, { rev: response.rev });
+  yield put({ type: types.CREATE_SESSION, session: session })
+}
+
+export function* watchCreateSession() {
+  yield takeLatest(types.CREATE_SESSION_ASYNC, createSession)
+}
+
+// ---
+
+export function* addNote(action) {
+  const response = yield notesDB.put(action.note);
+  // TODO Error control
+  const note = Object.assign({}, action.note, { rev: response.rev });
+  yield put({ type: types.ADD_NOTE, note: note })
+}
+
+export function* watchAddNote() {
+  yield takeLatest(types.ADD_NOTE_ASYNC, addNote)
+}
+
+// ---
+
+export function* loadNotesBySession(action) {
+  const result = yield notesDB.find({
+    selector: { session: action.session._id },
+    // sort: ['name']
+  });
+  yield put({ type: types.LOAD_NOTES_BY_SESSION, notes: Immutable.List(result.docs) })
+}
+
+export function* watchLoadNotesBySession() {
+  yield takeLatest(types.LOAD_NOTES_BY_SESSION_ASYNC, loadNotesBySession)
+}
+
+// ---
+
+export default function* rootSaga() {
+  yield all([
+    watchLoadSessions(),
+    watchLoadNotesBySession(),
+    watchAddNote(),
+    watchCreateSession(),
+  ])
+}