import api from '../../utils/api' import { repackBySort } from './arrangements' const state = { all: [], loaded: false, singleShort: null, } const getters = { allShorts: state => state.all, allShortsBySlug: state => Object.values(state.all).reduce((bySlug, short) => { bySlug[short.slug] = short return bySlug }, {}), allShortsLoaded: state => state.loaded, } const actions = { getAllShorts({ commit }, { sortType, params }) { commit('CLEAR_SHORTS') commit('SHORTS_LOADED', false) const storeFetch = (shorts => { let repacked = repackBySort(shorts, sortType) commit('STORE_FETCHED_SHORTS', { shorts: repacked }) commit('SHORTS_LOADED', true) }) return api.getByType({ type: 'short', sort: sortType, params, cb: storeFetch }) }, getMoreShorts({ commit }, { sortType, params }) { const storeFetch = (shorts => { let repacked = shorts commit('ADD_TO_FETCHED_SHORTS', { shorts: repacked }) commit('SHORTS_LOADED', true) }) return api.getByType({ type: 'short', sort: sortType, params, cb: storeFetch }) }, getSingleShort({ commit }, id) { commit('CLEAR_SINGLE_SHORTS') commit('SHORTS_LOADED', false) api.getSingleType('short', id, short => { commit('STORE_FETCHED_SINGLE_SHORT', short) commit('SHORTS_LOADED', true) }) }, } const mutations = { ADD_TO_FETCHED_SHORTS(state, { shorts }) { state.all = [...state.all, ...shorts] }, STORE_FETCHED_SHORTS(state, { shorts }) { state.all = shorts }, STORE_FETCHED_SINGLE_SHORT(state, short) { state.singleShort = short }, CLEAR_SHORTS(state) { state.all = [] }, CLEAR_SINGLE_SHORTS(state) { state.singleShort = null }, SHORTS_LOADED(state, val) { state.loaded = val }, } export default { state, getters, actions, mutations }