import { Module, MutationTree, ActionTree, GetterTree } from 'vuex'; import { StateInterface } from 'src/store'; import { axios } from 'boot/axios'; import { AxiosResponse } from 'axios'; import { SessionStorage } from 'quasar'; export interface UserStateInterface { updateUserLoading: boolean; getUserLoading: boolean; currentUser?: FG.User; users: FG.User[]; } const state: UserStateInterface = { users: [], currentUser: SessionStorage.getItem('currentUser') || undefined, updateUserLoading: false, getUserLoading: false }; const mutations: MutationTree = { setCurrentUser(state, data: FG.User) { SessionStorage.set('currentUser', data); state.currentUser = data; }, clearCurrentUser(state) { SessionStorage.remove('currentUser'); state.currentUser = undefined; }, setUsers(state, data: FG.User[]) { state.users = data; }, setLoading( state, data: { key: 'updateUserLoading' | 'getUserLoading'; data: boolean } ) { state[data.key] = data.data; } }; const actions: ActionTree = { getCurrentUser({ commit, rootState }) { if (rootState.session.currentSession) { commit('setLoading', { key: 'getUserLoading', data: true }); axios .get(`/users/${rootState.session.currentSession.userid}`) .then((response: AxiosResponse) => { commit('setCurrentUser', response.data); }) .catch(err => { console.warn(err); }) .finally(() => { commit('setLoading', { key: 'getUserLoading', data: false }); }); } else { console.debug('User not logged in, can not get current_user.'); } }, getUsers({ commit }) { axios .get(`/users`) .then((response: AxiosResponse) => { commit('setUsers', response.data); }) .catch(err => { console.warn(err); }); }, updateUser({ commit, state, dispatch }, data) { commit('setLoading', { key: 'updateUserLoading', data: true }); if (!state.currentUser) throw 'Not logged in'; axios .put(`/users/${state.currentUser.userid}`, data) .then(() => { void dispatch('getCurrentUser'); }) .catch(error => { console.log(error); }) .finally(() => { commit('setLoading', { key: 'updateUserLoading', data: false }); }); } }; const getters: GetterTree = { currentUser({ currentUser }) { return currentUser; }, users({ users }) { return users; }, loading({ updateUserLoading, getUserLoading }) { return updateUserLoading || getUserLoading; }, displayName({ currentUser }) { return currentUser?.display_name; }, permissions({ currentUser }) { let permissions: string[] = []; if (currentUser) { currentUser.roles.forEach(role => { permissions = permissions.concat(role.permissions); }); } return permissions; } }; const userStore: Module = { namespaced: true, actions, getters, mutations, state }; export default userStore;