import update from 'immutability-helper'; import * as _ from 'lodash'; import { APPEND_DATASET_PAGE, RECEIVE_DATASET, APPEND_ACCESSIONS_PAGE, RECEIVE_DATASET_OVERVIEW, } from 'datasets/constants'; import { LOGIN_APP, LOGIN_USER, LOGOUT } from 'constants/login'; import Dataset from 'model/catalog/Dataset'; import { AccessionRef } from 'model/accession/AccessionRef'; import Page from 'model/Page'; import FilteredPage from 'model/FilteredPage'; import ApiCall from 'model/ApiCall'; import DatasetOverview from 'model/catalog/DatasetOverview'; import {dereferenceReferences} from 'utilities'; const INITIAL_STATE: { dataset: ApiCall, paged: ApiCall>, overview: ApiCall, accessionRefs: ApiCall>, } = { dataset: null, paged: null, overview: null, accessionRefs: null, }; function datasetsPublic(state = INITIAL_STATE, action: { type?: string, payload?: any } = { type: '', payload: {} }) { switch (action.type) { case LOGIN_USER: case LOGIN_APP: case LOGOUT: { return update(state, { $set: INITIAL_STATE }); } case RECEIVE_DATASET: { const {apiCall} = action.payload; const receivedIndex = state.paged && state.paged.data ? _.findIndex(state.paged.data.content, (item) => item.uuid === apiCall.uuid) : -1; const mustRemoveAccessions = state.dataset && state.dataset.data && apiCall.data && (apiCall.uuid !== state.dataset.data.uuid); if (receivedIndex !== -1) { return update(state, { dataset: { $set: apiCall }, accessionRefs: { $set: mustRemoveAccessions ? null : state.accessionRefs }, paged: { content: { [receivedIndex]: { $set: apiCall.data }, }, loading: {$set: false}, }, }); } else { return update(state, { dataset: { $set: apiCall }, accessionRefs: { $set: mustRemoveAccessions ? null : state.accessionRefs }, }); } } case APPEND_ACCESSIONS_PAGE: { const {apiCall: {loading, error, timestamp, data}} = action.payload; return update(state, { accessionRefs: { $set: { loading, error, timestamp, data: Page.merge(state.accessionRefs && state.accessionRefs.data, data), }, }, }); } case APPEND_DATASET_PAGE: { const {apiCall: {loading, error, timestamp, data}} = action.payload; if (data) { dereferenceReferences(data.content, 'owner'); } return update(state, { paged: { $set: { loading, error, timestamp, data: FilteredPage.merge(state.paged && state.paged.data, data), }, }, }); } case RECEIVE_DATASET_OVERVIEW: { const { apiCall: { loading, error, timestamp, data } } = action.payload; return update(state, { overview: { $set: { loading, error, timestamp, data: data !== undefined ? data : state.overview && state.overview.data, }, }, }); } default: return state; } } export default datasetsPublic;