cheetah-framework
Version:
Cheetah Framework JS used in all our applications
147 lines (113 loc) • 3.06 kB
JavaScript
import config from '@cheetah/config'
const gridConfig = config.grid
class FakeResponse {
constructor (data) {
this.data = data
}
}
// ACTIONS
function buildActions (Model) {
let FetchPromise = false
const actions = {}
actions['fetch'] = ({ commit, state }, fetchOptions) => {
fetchOptions = _.defaults(fetchOptions, {
force: false,
criteria: []
})
if (FetchPromise !== false && !fetchOptions.force) {
return FetchPromise
}
if (!state.loaded || fetchOptions.force === true) {
// return a Promise object
return (FetchPromise = Model.all([], { per_page: 10000, page: 1 }).then(response => {
commit('LOAD_ITEMS', response.data[gridConfig.keys.items])
FetchPromise = false
return response
}).catch(error => {
FetchPromise = false
// Should be throw for further catch
throw error
}))
}
// Items already fetched - just return items
return Promise.resolve(new FakeResponse(state.items))
}
actions['reloadItem'] = ({ state, commit }, id) => {
return Model.get(id, null, 'list').then(response => {
commit('UPDATE', response.data)
return response
})
}
actions['store'] = ({ commit }, payload) => {
const instance = new Model(payload)
return instance.store()
}
actions['update'] = ({ commit }, payload) => {
const instance = new Model(_.pick(payload, Model.idKey))
return instance.update(_.cloneDeep(payload)).then(response => {
return response
})
}
actions['destroy'] = ({ commit }, payload) => {
const instance = new Model(payload)
return instance.destroy()
}
return actions
}
// GETTERS
function buildGetters (Model) {
const getters = {}
getters['getItems'] = state => {
return state.items
}
getters['getById'] = state => id => {
return state.items.find(item => item[Model.idKey] === id)
}
return getters
}
// MUTATIONS
function buildMutations (Model) {
const mutations = {}
mutations['LOAD_ITEMS'] = (state, payload) => {
state.items = payload.map(item => new Model(item))
state.loaded = true
}
mutations['STORE'] = (state, payload) => {
if (!state.loaded) {
return
}
state.items.push(new Model(payload))
}
mutations['UPDATE'] = (state, payload) => {
if (!state.loaded) {
return
}
const index = _.findIndex(state.items, _.pick(payload, Model.idKey))
if (index === -1) {
// Element not in store
state.items.push(new Model(payload))
} else {
// Element in store
state.items.splice(index, 1, new Model(payload))
}
}
mutations['DELETE'] = (state, payload) => {
if (!state.loaded) {
return
}
const index = _.findIndex(state.items, _.pick(payload, Model.idKey))
if (index !== -1) {
state.items.splice(index, 1)
}
}
mutations['FLUSH'] = state => {
state.loaded = false
state.items.splice(0)
}
return mutations
}
export {
buildGetters,
buildMutations,
buildActions
}