chore: 脚手架

This commit is contained in:
dap
2024-08-07 08:57:56 +08:00
parent 4bd4f7490b
commit c31259598b
83 changed files with 2127 additions and 225 deletions

View File

@@ -10,7 +10,7 @@ import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { getAccessCodes, getUserInfo, login } from '#/api';
import { doLogout, getUserInfo, login } from '#/api';
import { $t } from '#/locales';
export const useAuthStore = defineStore('auth', () => {
@@ -33,40 +33,35 @@ export const useAuthStore = defineStore('auth', () => {
let userInfo: null | UserInfo = null;
try {
loginLoading.value = true;
const { accessToken, refreshToken } = await login(params);
const { access_token } = await login(params);
// 如果成功获取到 accessToken
if (accessToken) {
// 将 accessToken 存储到 accessStore 中
accessStore.setAccessToken(accessToken);
accessStore.setRefreshToken(refreshToken);
// accessToken 存储到 accessStore 中
accessStore.setAccessToken(access_token);
accessStore.setRefreshToken(access_token);
// 获取用户信息并存储到 accessStore 中
const [fetchUserInfoResult, accessCodes] = await Promise.all([
fetchUserInfo(),
getAccessCodes(),
]);
// 获取用户信息并存储到 accessStore 中
userInfo = await fetchUserInfo();
/**
* 设置用户信息
*/
userStore.setUserInfo(userInfo);
/**
* 在这里设置权限
*/
accessStore.setAccessCodes(userInfo.permissions);
userInfo = fetchUserInfoResult;
if (accessStore.loginExpired) {
accessStore.setLoginExpired(false);
} else {
onSuccess ? await onSuccess?.() : await router.push(DEFAULT_HOME_PATH);
}
userStore.setUserInfo(userInfo);
accessStore.setAccessCodes(accessCodes);
if (accessStore.loginExpired) {
accessStore.setLoginExpired(false);
} else {
onSuccess
? await onSuccess?.()
: await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
}
if (userInfo?.realName) {
notification.success({
description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
duration: 3,
message: $t('authentication.loginSuccess'),
});
}
if (userInfo?.realName) {
notification.success({
description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
duration: 3,
message: $t('authentication.loginSuccess'),
});
}
} finally {
loginLoading.value = false;
@@ -78,21 +73,38 @@ export const useAuthStore = defineStore('auth', () => {
}
async function logout() {
resetAllStores();
accessStore.setLoginExpired(false);
try {
await doLogout();
} catch (error) {
console.error(error);
} finally {
resetAllStores();
accessStore.setLoginExpired(false);
// 回登陆页带上当前路由地址
await router.replace({
path: LOGIN_PATH,
query: {
redirect: encodeURIComponent(router.currentRoute.value.fullPath),
},
});
// 回登陆页带上当前路由地址
await router.replace({
path: LOGIN_PATH,
query: {
redirect: encodeURIComponent(router.currentRoute.value.fullPath),
},
});
}
}
async function fetchUserInfo() {
let userInfo: null | UserInfo = null;
userInfo = await getUserInfo();
const { permissions = [], roles = [], user } = await getUserInfo();
/**
* 从后台user -> vben user转换
*/
const userInfo: UserInfo = {
avatar: user.avatar ?? '',
permissions,
realName: user.nickName,
roles,
userId: user.userId,
username: user.userName,
};
userStore.setUserInfo(userInfo);
return userInfo;
}

View File

@@ -1 +1,2 @@
export * from './auth';
export * from './notify';

View File

@@ -0,0 +1,119 @@
import type { NotificationItem } from '@vben/layouts';
import { computed, ref, watch } from 'vue';
import { useAppConfig } from '@vben/hooks';
import { useAccessStore } from '@vben/stores';
import { useEventSource } from '@vueuse/core';
import { notification } from 'ant-design-vue';
import dayjs from 'dayjs';
import { random } from 'lodash-es';
import { defineStore } from 'pinia';
const { apiURL, clientId } = useAppConfig(
import.meta.env,
import.meta.env.PROD,
);
export const useNotifyStore = defineStore(
'app-notify',
() => {
const notificationList = ref<NotificationItem[]>([]);
/**
* 开始监听sse消息
*/
function startListeningMessage() {
const accessStore = useAccessStore();
const token = accessStore.accessToken;
const sseAddr = `${apiURL}/resource/sse?clientid=${clientId}&Authorization=Bearer ${token}`;
const { data } = useEventSource(sseAddr, [], {
autoReconnect: {
delay: 1000,
onFailed() {
console.log('sse重连失败.');
},
retries: 3,
},
});
watch(data, (message) => {
if (!message) return;
console.log(`接收到消息: ${message}`);
notification.success({
description: message,
duration: 3,
message: '收到新消息',
});
notificationList.value.push({
// 随机头像
avatar: `https://api.multiavatar.com/${random(0, 10_000)}.png`,
date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
isRead: false,
message,
title: '消息',
});
data.value = null;
});
}
/**
* 设置全部已读
*/
function setAllRead() {
notificationList.value.forEach((item) => {
item.isRead = true;
});
}
/**
* 设置单条消息已读
* @param item 通知
*/
function setRead(item: NotificationItem) {
!item.isRead && (item.isRead = true);
}
/**
* 清空全部消息
*/
function clearAllMessage() {
notificationList.value = [];
}
/**
* 只需要空实现即可
* 否则会在退出登录清空所有
*/
function $reset() {
// notificationList.value = [];
}
/**
* 显示小圆点
*/
const showDot = computed(() =>
notificationList.value.some((item) => !item.isRead),
);
return {
$reset,
clearAllMessage,
notificationList,
setAllRead,
setRead,
showDot,
startListeningMessage,
};
},
{
persist: {
paths: ['notificationList'],
},
},
);