Home Reference Source

application/redux/reducers/global-search-reducers.js

import _ from 'lodash';
import Immutable from 'immutable';
import {
GLOBAL_SEARCH_REQUEST,
GLOBAL_SEARCH_RECEIVE,
GLOBAL_SEARCH_INVALIDATE,
GLOBAL_SEARCH_REMEMBER,
GLOBAL_SEARCH_RECEIVE_PAGINATION
} from './../actions/global-search-actions';

const PER_PAGE = 20;

export function globalSearch(state = null, action) {
    if (state === null) {
        state = {
            isFetching: false,
            didInvalidate: false,
            didSearch: false,
            items: Immutable.fromJS({}),
            page: 0,
            pagination: {
                before: 0,
                current: 0,
                first: 0,
                last: 0,
                limit: 0,
                next: 0,
                total_items: 0,
                total_pages: 0
            },
            order: "modified_at",
            dir: "desc",
            filter: false,
            navigationQuery: {}
        };
    }

    let newState;

    switch (action.type) {
        case GLOBAL_SEARCH_RECEIVE_PAGINATION:
            return Object.assign({}, state, {
                pagination: {
                    'before': action.payload.before,
                    'current': action.payload.current,
                    'first': action.payload.first,
                    'last': action.payload.last,
                    'limit': action.payload.limit,
                    'next': action.payload.next,
                    'total_items': action.payload.total_items,
                    'total_pages': action.payload.total_pages,
                }
            });
        case GLOBAL_SEARCH_REMEMBER:
            return Object.assign({}, state, {
                navigationQuery: action.payload.query
            });
        case GLOBAL_SEARCH_INVALIDATE:
            return Object.assign({}, state, {
                didInvalidate: true,
            });
        case GLOBAL_SEARCH_REQUEST:
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            });
        case GLOBAL_SEARCH_RECEIVE:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                didSearch: true,
                items: action.payload.items
            });
    }

    return state;
};