Files
client-web/src/modules/notifications/store/notifications.ts
T

40 lines
1.1 KiB
TypeScript

import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { getMyUnreadNotificationCount } from '../api/notifications'
export const useNotificationsStore = defineStore('client-notifications', () => {
const unreadCount = ref<number | null>(null)
const loading = ref(false)
const errorMessage = ref('')
const hasUnread = computed(() => (unreadCount.value ?? 0) > 0)
let pending: Promise<void> | null = null
async function refreshUnreadCount(afterMutation = false): Promise<void> {
if (pending) {
if (!afterMutation) return pending
await pending
return refreshUnreadCount()
}
pending = loadUnreadCount().finally(() => { pending = null })
return pending
}
async function loadUnreadCount() {
loading.value = true
errorMessage.value = ''
try {
unreadCount.value = await getMyUnreadNotificationCount()
} catch (error) {
unreadCount.value = null
errorMessage.value = error instanceof Error ? error.message : '未读数量加载失败'
} finally {
loading.value = false
}
}
return { unreadCount, hasUnread, loading, errorMessage, refreshUnreadCount }
})