78 lines
2.4 KiB
TypeScript
Raw Normal View History

import { ActionContext, ActionTree } from 'vuex'
2021-08-11 22:21:26 +02:00
2021-08-11 21:12:20 +02:00
import { ROOT_STORE, USER_STORE } from '@/store/constants'
2021-08-11 22:21:26 +02:00
import { IRootState } from '@/store/modules/root/interfaces'
2021-08-11 21:12:20 +02:00
import {
ILoginOrRegisterData,
IUserActions,
IUserState,
} from '@/store/modules/user/interfaces'
import { handleError } from '@/utils'
import authApi from '@/api/authApi'
2021-08-11 22:21:26 +02:00
import api from '@/api/defaultApi'
import router from '@/router'
export const actions: ActionTree<IUserState, IRootState> & IUserActions = {
2021-08-14 19:24:19 +02:00
[USER_STORE.ACTIONS.CHECK_AUTH_USER](
context: ActionContext<IUserState, IRootState>
): void {
if (
window.localStorage.authToken &&
!context.getters[USER_STORE.GETTERS.IS_AUTHENTICATED]
) {
context.commit(
USER_STORE.MUTATIONS.UPDATE_AUTH_TOKEN,
window.localStorage.authToken
)
context.dispatch(USER_STORE.ACTIONS.GET_USER_PROFILE)
}
},
[USER_STORE.ACTIONS.GET_USER_PROFILE](
context: ActionContext<IUserState, IRootState>
): void {
2021-08-11 21:12:20 +02:00
context.commit(ROOT_STORE.MUTATIONS.EMPTY_ERROR_MESSAGE)
authApi
.get('auth/profile')
.then((res) => {
if (res.data.status === 'success') {
context.commit(
USER_STORE.MUTATIONS.UPDATE_AUTH_USER_PROFILE,
res.data.data
)
2021-08-11 21:12:20 +02:00
} else {
handleError(context, null)
}
})
2021-08-11 21:12:20 +02:00
.catch((error) => handleError(context, error))
},
[USER_STORE.ACTIONS.LOGIN_OR_REGISTER](
context: ActionContext<IUserState, IRootState>,
data: ILoginOrRegisterData
): void {
2021-08-11 21:12:20 +02:00
context.commit(ROOT_STORE.MUTATIONS.EMPTY_ERROR_MESSAGE)
api
.post(`/auth/${data.actionType}`, data.formData)
.then((res) => {
2021-08-11 21:12:20 +02:00
if (res.data.status === 'success') {
const token = res.data.auth_token
window.localStorage.setItem('authToken', token)
context.commit(USER_STORE.MUTATIONS.UPDATE_AUTH_TOKEN, token)
context
.dispatch(USER_STORE.ACTIONS.GET_USER_PROFILE)
.then(() => router.push('/'))
2021-08-11 21:12:20 +02:00
} else {
handleError(context, null)
}
})
2021-08-11 21:12:20 +02:00
.catch((error) => handleError(context, error))
},
2021-08-14 18:58:59 +02:00
[USER_STORE.ACTIONS.LOGOUT](
context: ActionContext<IUserState, IRootState>
): void {
localStorage.removeItem('authToken')
context.commit(USER_STORE.MUTATIONS.CLEAR_AUTH_USER_TOKEN)
context.commit(ROOT_STORE.MUTATIONS.EMPTY_ERROR_MESSAGE)
router.push('/login')
},
}