listReducer.js 1.98 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,

} = 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) {
					console.log('......find....');
					originAry[i].isPraise = 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)
		}

    }

    return state;
}