Skip to content

Instantly share code, notes, and snippets.

@beardcoder

beardcoder/store.ts

Last active Mar 10, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.