designtopack/src/router/router.js

36 lines
838 B
JavaScript
Raw Normal View History

import { createWebHistory, createRouter } from 'vue-router';
import routes from './routes';
import { useApiStore } from '../stores/api';
import { usePageStore } from '../stores/page';
import { useUserStore } from '../stores/user';
import { getActivePinia } from 'pinia';
2024-09-17 17:03:13 +02:00
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach(async (to, from, next) => {
const pinia = getActivePinia();
2024-10-28 15:33:52 +01:00
const pageStore = usePageStore(pinia);
const userStore = useUserStore(pinia);
2024-09-17 17:03:13 +02:00
if (to.path === '/login') next();
const api = useApiStore(pinia);
2024-09-17 17:03:13 +02:00
try {
2024-10-28 15:33:52 +01:00
const res = await api.fetchData(to.path);
2024-09-17 17:03:13 +02:00
2025-04-30 16:21:56 +02:00
if (!res.user) next('/login');
2024-10-28 15:33:52 +01:00
pageStore.page = res.page;
userStore.user = res.user;
2024-09-17 17:03:13 +02:00
next();
} catch (error) {
console.error(error);
next(false);
}
});
export { router };