Skip to content

Commit e3ac8a1

Browse files
committed
Improve router error handling & tidy
1 parent 1ecfe08 commit e3ac8a1

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

src/router/index.js

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,35 +23,29 @@
2323
* https://router.vuejs.org/en/
2424
*/
2525

26-
// Lib imports
2726
import { createRouter, createWebHashHistory } from 'vue-router'
2827
import NProgress from 'nprogress'
29-
import { store } from '@/store/index'
3028

3129
import 'nprogress/css/nprogress.css'
3230

33-
// Routes
34-
import paths from './paths'
31+
import paths from '@/router/paths'
32+
import { store } from '@/store/index'
3533
import { Alert } from '@/model/Alert.model'
3634

3735
NProgress.configure({ showSpinner: false })
3836

39-
function route (path) {
40-
const copy = Object.assign({}, path)
41-
const view = copy.view
42-
return Object.assign(copy, {
43-
name: path.name || view,
44-
component: (resolve) => import(
45-
`@/views/${view}.vue`
46-
).then(resolve)
47-
})
37+
function getRoute (path) {
38+
return {
39+
...path,
40+
name: path.name || path.view,
41+
component: () => import(`@/views/${path.view}.vue`)
42+
}
4843
}
4944

5045
// Create a new router
5146
const router = createRouter({
5247
history: createWebHashHistory(),
53-
routes: paths.map(path => route(path)),
54-
// .concat([{ path: '*', redirect: '/dashboard' }]),
48+
routes: paths.map(getRoute),
5549
scrollBehavior (to, from, savedPosition) {
5650
if (savedPosition) {
5751
return savedPosition
@@ -66,15 +60,17 @@ const router = createRouter({
6660
router.beforeEach(async (to, from) => {
6761
NProgress.start()
6862
if (!store.state.user.user) {
69-
try {
70-
const user = await router.app.config.globalProperties.$userService.getUserProfile()
71-
store.commit('user/SET_USER', user)
72-
} catch (err) {
73-
store.dispatch('setAlert', new Alert(err, 'error'))
74-
}
63+
const user = await router.app.config.globalProperties.$userService.getUserProfile()
64+
// TODO: catch error getting user profile and redirect to static error page
65+
store.commit('user/SET_USER', user)
7566
}
76-
if (!store.state.user.user.permissions.includes('read') && to.name !== 'noAuth') {
77-
return { name: 'noAuth' }
67+
if (!store.state.user.user.permissions?.includes('read')) {
68+
if (to.name !== 'noAuth') { // Avoid infinite redirect?
69+
return { name: 'noAuth' }
70+
}
71+
} else if (to.name === 'noAuth') {
72+
// If authorized, redirect no-auth page to home page
73+
return { path: '/' }
7874
}
7975

8076
if (to.name) {
@@ -96,4 +92,9 @@ router.afterEach(() => {
9692
NProgress.done()
9793
})
9894

95+
router.onError((err, to, from) => {
96+
store.dispatch('setAlert', new Alert(err, 'error'))
97+
NProgress.done()
98+
})
99+
99100
export default router

0 commit comments

Comments
 (0)