Store Pattern für vuex store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ActionTree, MutationTree } from '~/node_modules/vuex'; | |
export const apiRoutes = { | |
requests: '/api/requests', | |
} | |
export interface RequestState { | |
requests: [] | null; | |
} | |
export const state = (): RequestState => ({ | |
requests: null, | |
}); | |
export const mutations: MutationTree<RequestState> = { | |
SET(store, payload: { type: string; value: any }) { | |
const { type, value } = payload; | |
store[type] = value; | |
}, | |
ADD(store, payload: { type: string; value: any }) { | |
const { type, value } = payload; | |
store[type].push(value); | |
}, | |
UPDATE(store, payload: { type: string; value: any; key: any }) { | |
const { type, value, key } = payload; | |
const objIndex = store[type].findIndex(obj => obj[key] === value[key]); | |
store[type][objIndex] = value; | |
}, | |
REMOVE(store, payload: { type: string; value: any; key: any }) { | |
const { type, value, key } = payload; | |
store[type] = store[type].filter(item => item[key] !== value[key]); | |
}, | |
}; | |
export const actions: ActionTree<RequestState, RequestState> = { | |
fetch({ commit }) { | |
return this.$axios | |
.$get(apiRoutes.requests) | |
.then(res => { | |
commit('SET', { type: 'requests', value: res['hydra:members'] }); | |
return res; | |
}) | |
.catch(() => { | |
this.dispatch('notify/error', 'Fehler beim laden der Anfragen'); | |
}); | |
}, | |
create({ commit }, payload) { | |
return this.$axios | |
.$post(apiRoutes.requests, payload) | |
.then(res => { | |
commit('ADD', { type: 'requests', value: res }); | |
return res; | |
}) | |
.catch(() => { | |
this.dispatch('notify/error', 'Fehler beim erstellen der Anfrage'); | |
}); | |
}, | |
update({ commit }, payload) { | |
return this.$axios | |
.$put(payload['@id'] ? payload['@id'] : '', payload) | |
.then(res => { | |
commit('UPDATE', { type: 'requests', value: payload, key: 'id' }); | |
return res; | |
}) | |
.catch(() => { | |
this.dispatch('notify/error', 'Fehler beim updaten der Anfrage'); | |
}); | |
}, | |
delete({ commit }, payload) { | |
return this.$axios | |
.$delete(payload['@id'] ? payload['@id'] : '') | |
.then(res => { | |
commit('REMOVE', { type: 'requests', value: payload, key: 'id' }); | |
return res; | |
}) | |
.catch(() => { | |
this.dispatch('notify/error', 'Fehler beim löschen der Anfrage'); | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment