import { Module, MutationTree, ActionTree, GetterTree } from 'vuex'; import { StateInterface } from 'src/store'; import { axios } from 'src/boot/axios'; import { AxiosResponse } from 'axios'; import { Router } from 'src/router'; export interface SessionInterface { sessions: FG.Session[]; loading: boolean; } const state: SessionInterface = { sessions: [], loading: false }; const mutations: MutationTree = { setSessions(state, sessions: FG.Session[]) { state.sessions = sessions; }, setLoading(state, value: boolean) { state.loading = value; } }; const actions: ActionTree = { getSessions({ commit, rootState, dispatch }) { commit('setLoading', true); axios .get('/auth') .then((response: AxiosResponse) => { console.log(response.data); response.data.forEach(session => { session.expires = new Date(session.expires); }); commit('setSessions', response.data); const currentSession = response.data.find((session: FG.Session) => { return session.token === rootState.user.session.token; }); if (currentSession) { void dispatch('user/setSession', currentSession, { root: true }); } }) .catch(error => { console.exception(error); }) .finally(() => { commit('setLoading', false); }); }, deleteSession({ commit, dispatch, rootState }, token: string) { commit('setLoading', true); axios .delete(`/auth/${token}`) .then(() => { if (token === rootState.user.session.token) { void dispatch('user/setSession', null, { root: true }); Router.go(0); } else { void dispatch('getSessions'); } }) .catch(error => { console.exception(error); }) .finally(() => { commit('setLoading', false); }); } }; const getters: GetterTree = { sessions(state) { return state.sessions; }, loading(state) { return state.loading; } }; const sessions: Module = { namespaced: true, state, mutations, actions, getters }; export default sessions;