listReducer.js 2.44 KB
'use strict';

import InitialState from './listInitialState';
import Immutable, {Map} from 'immutable';

const {
	SET_LIST_TYPE,
	SET_AUTHOR_ID,
    SET_TAG,

	GET_ARTICLE_LIST_REQUEST,
    GET_ARTICLE_LIST_SUCCESS,
    GET_ARTICLE_LIST_FAILURE,

	LIKE_ARTICLE,

	GET_AUTHOR_REQUEST,
	GET_AUTHOR_SUCCESS,
	GET_AUTHOR_FAILURE,
} = require('../../constants/actionTypes').default;

const initialState = new InitialState;

export default function listReducer(state=initialState, action) {
    switch(action.type) {
    	case SET_LIST_TYPE: {
    		return state.set('type', action.payload);
    	}

    	case SET_AUTHOR_ID: {
    		return state.set('authorId', action.payload);
    	}

    	case SET_TAG: {
    		return state.set('tag', action.payload);
    	}

    	case GET_ARTICLE_LIST_REQUEST: {
    		return state.setIn(['articles', 'isFetching'], true)
			.setIn(['articles', 'error'], null)
			.setIn(['articles', 'ptr'], action.payload);
    	}

    	case GET_ARTICLE_LIST_SUCCESS: {
    		let {
				list,
				currentPage,
				pageCount,
				total,
				endReached,
			} = action.payload;

			let newState = state.setIn(['articles', 'isFetching'], false)
			.setIn(['articles', 'error'], null)
			.setIn(['articles', 'list'], Immutable.fromJS(list))
			.setIn(['articles', 'currentPage'], currentPage)
			.setIn(['articles', 'pageCount'], pageCount)
			.setIn(['articles', 'total'], total)
			.setIn(['articles', 'endReached'], endReached);

			return newState;
		}

		case LIKE_ARTICLE: {
			let {
				article_id,
				isLike,
			} = action.payload;
			let originAry = state.get('articles').get('list').toJS();
			for (var i = 0; i < originAry.length; i++) {
				if (originAry[i].id == article_id) {
					originAry[i].isFavor = isLike?'Y':'N';
				}
			}
			let newState = state.setIn(['articles', 'list'], Immutable.fromJS(originAry));

			return newState;
		}

			break;

		case GET_ARTICLE_LIST_FAILURE: {
			return state.setIn(['articles', 'isFetching'], false)
			.setIn(['articles', 'error'], action.payload)
		}

		case GET_AUTHOR_REQUEST: {
			return state.setIn(['author', 'isFetching'], true)
			.setIn(['author', 'error'], null);
		}

		case GET_AUTHOR_SUCCESS: {
			return state.setIn(['author', 'isFetching'], false)
			.setIn(['author', 'error'], null)
			.setIn(['author', 'data'], Immutable.fromJS(action.payload));
		}

		case GET_AUTHOR_FAILURE: {
			return state.setIn(['author', 'isFetching'], false)
			.setIn(['author', 'error'], action.payload);
		}
    }

    return state;
}