admin-vben5/apps/web-antd/src/store/notify.ts

120 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-08-07 08:57:56 +08:00
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: '收到新消息',
});
2024-08-07 10:27:53 +08:00
notificationList.value.unshift({
2024-08-07 08:57:56 +08:00
// 随机头像
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'],
},
},
);