github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/blockapps-ba-master/ui/src/scenes/Login/login.saga.js (about)

     1  import { takeLatest, put, call } from 'redux-saga/effects';
     2  import {
     3    USER_LOGIN_SUBMIT,
     4    userLoginSuccess,
     5    userLoginFailure
     6  } from './login.actions';
     7  import { browserHistory } from 'react-router';
     8  import { API_URL, API_MOCK } from '../../environment';
     9  import { handleApiError } from '../../lib/apiErrorHandler';
    10  import { showLoading, hideLoading } from 'react-redux-loading-bar';
    11  
    12  const loginUrl = API_URL + '/login';
    13  
    14  function loginApiCall(username,password) {
    15    if(API_MOCK) {
    16      return new Promise(function(resolve, reject){
    17        resolve({
    18          data: {
    19            authenticate: true,
    20            user: {
    21              username: 'Supplier1',
    22              role: 'Supplier'
    23            }
    24          }
    25        });
    26      });
    27    }
    28    else {
    29      return fetch(loginUrl, {
    30        method: 'POST',
    31        headers: {
    32          'Content-Type': 'application/json;charset=utf-8',
    33          'Accept': 'application/json'
    34        },
    35        body: JSON.stringify({ username, password})
    36      })
    37      .then(handleApiError)
    38      .then(function(response) {
    39        return response.json();
    40      })
    41      .catch(function(error){
    42        throw error;
    43      });
    44    }
    45  }
    46  
    47  function* submitLogin(action) {
    48    try {
    49      yield put(showLoading());
    50  
    51      const response = yield call(loginApiCall, action.username, action.password);
    52      yield put(hideLoading());
    53      if(response.data.authenticate) {
    54        yield put(userLoginSuccess(response.data.user.username, response.data.user.role));
    55      }
    56    }
    57    catch(err)
    58    {
    59      yield put(userLoginFailure(err));
    60      yield put(hideLoading());
    61    }
    62    browserHistory.push('/projects');
    63  }
    64  
    65  export default function* watchLoginSubmit() {
    66    yield takeLatest(USER_LOGIN_SUBMIT, submitLogin);
    67  }