Home Reference Source

application/redux/reducers/note-comment-reducers.js

import _ from 'lodash';
import Immutable from 'immutable';
import {
    NOTE_COMMENTS_REQUEST,
    NOTE_COMMENTS_RECEIVE,
    NOTE_COMMENT_RECEIVE,
    NOTE_COMMENTS_INVALIDATE,
    NOTE_COMMENT_SELECTED,
    NOTE_COMMENTS_IS_FETCHING
} from './../actions/note-comment-actions';

const PER_PAGE = 20;

export function noteComments(state = null, action) {
    if (state === null) {
        state = {
            isFetching: false,
            didInvalidate: false,
            items: Immutable.fromJS({}),
            selected: false,
            order: "name",
            dir: "asc",
            filter: false
        };
    }

    let newState;

    switch (action.type) {
        case NOTE_COMMENTS_IS_FETCHING:
            return Object.assign({}, state, {
                isFetching: action.payload.isFetching
            });
        case NOTE_COMMENTS_INVALIDATE:
            return Object.assign({}, state, {
                didInvalidate: true,
            });
        case NOTE_COMMENTS_REQUEST:
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });
        case NOTE_COMMENT_SELECTED: {
            return Object.assign({}, state, {
                selected: action.payload.selected
            });
        }
        case NOTE_COMMENT_RECEIVE:
            const noteComment = action.payload.noteComment;
            let found = false;
            const allNotes = state.items.map((item, i) => {
                if (item.get('uuid') == noteComment.get('uuid')) {
                    found = true;
                    return noteComment;
                }
                return item;
            });

            if (!found) {
                let temp = allNotes.toList().asMutable();
                temp.push(noteComment);
                action.payload.noteComments = temp.asMutable();
            } else {
                action.payload.noteComments = allNotes;
            }
        case NOTE_COMMENTS_RECEIVE:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                items: action.payload.noteComments
            });
    }

    return state;
};