23
23
* https://router.vuejs.org/en/
24
24
*/
25
25
26
- // Lib imports
27
26
import { createRouter , createWebHashHistory } from 'vue-router'
28
27
import NProgress from 'nprogress'
29
- import { store } from '@/store/index'
30
28
31
29
import 'nprogress/css/nprogress.css'
32
30
33
- // Routes
34
- import paths from './paths '
31
+ import paths from '@/router/paths'
32
+ import { store } from '@/store/index '
35
33
import { Alert } from '@/model/Alert.model'
36
34
37
35
NProgress . configure ( { showSpinner : false } )
38
36
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
+ }
48
43
}
49
44
50
45
// Create a new router
51
46
const router = createRouter ( {
52
47
history : createWebHashHistory ( ) ,
53
- routes : paths . map ( path => route ( path ) ) ,
54
- // .concat([{ path: '*', redirect: '/dashboard' }]),
48
+ routes : paths . map ( getRoute ) ,
55
49
scrollBehavior ( to , from , savedPosition ) {
56
50
if ( savedPosition ) {
57
51
return savedPosition
@@ -66,15 +60,17 @@ const router = createRouter({
66
60
router . beforeEach ( async ( to , from ) => {
67
61
NProgress . start ( )
68
62
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 )
75
66
}
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 : '/' }
78
74
}
79
75
80
76
if ( to . name ) {
@@ -96,4 +92,9 @@ router.afterEach(() => {
96
92
NProgress . done ( )
97
93
} )
98
94
95
+ router . onError ( ( err , to , from ) => {
96
+ store . dispatch ( 'setAlert' , new Alert ( err , 'error' ) )
97
+ NProgress . done ( )
98
+ } )
99
+
99
100
export default router
0 commit comments