Skip to content

Instantly share code, notes, and snippets.

@beardcoder
Last active March 10, 2020 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beardcoder/077e429dcde2a9646880fcc162d9d438 to your computer and use it in GitHub Desktop.
Save beardcoder/077e429dcde2a9646880fcc162d9d438 to your computer and use it in GitHub Desktop.
Store Pattern für vuex store
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