client/src/sagas/authSaga.js
author ymh <ymh.work@gmail.com>
Mon, 26 Jun 2017 15:21:06 +0200
changeset 87 dbcee57de2c6
child 89 06f609adfbf8
permissions -rw-r--r--
Add first implementation of network monitor

import { put, take, all } from 'redux-saga/effects'
import * as types from '../constants/actionTypes';

// ---

function* watchLoginSubmit() {
  while (true) {
    const { username, password } = yield take(types.AUTH_LOGIN_SUBMIT);
    yield put({ type: types.AUTH_LOGIN_REQUEST, username, password });
  }
}

function* watchLoginRequest(context) {
  while (true) {
    try {

        const { username, password } = yield take(types.AUTH_LOGIN_REQUEST);
        const client = context.client;
        const response = yield client.post('/api/auth/login/', { username, password });

        const actions = [{
          type: types.AUTH_STORE_TOKEN_ASYNC,
          token: response.token,
        },
        {
          type: types.AUTH_LOGIN_SUCCESS,
          user: response.user,
          token: response.token,
        }];

        yield all(actions.map(action => put(action)));
        context.history.push('/sessions');

    } catch(e) {
        yield put({ type: types.AUTH_LOGIN_ERROR, error: e });
    }
  }
}

function* watchStoreToken() {
  while (true) {
    const { token } = yield take(types.AUTH_STORE_TOKEN_ASYNC);
    yield put({ type: types.AUTH_STORE_TOKEN, token });
  }
}

function* watchUpdateSettings(context) {
  while (true) {
    const { username, firstname, lastname } = yield take(types.USER_UPDATE_SETTINGS_ASYNC);
    const client = context.client;
    try {
      yield client.put('/api/auth/user/', {
        username,
        first_name: firstname,
        last_name: lastname
      });
      yield put({ type: types.USER_UPDATE_SETTINGS, firstname, lastname });
    } catch (e) {

    }
  }
}

// ---

export default function* rootSaga(context) {
  yield all([
    watchLoginSubmit(),
    watchLoginRequest(context),
    watchStoreToken(),
    watchUpdateSettings(context),
  ])
}