feat(notifications): migrate to backend API
This commit is contained in:
+37
-26
@@ -1,33 +1,44 @@
|
||||
import { allow, deny } from "@/lib/decision"
|
||||
import type { Notification } from "@/lib/types"
|
||||
import { useAuthStore } from "@/store/auth"
|
||||
import { useNotificationStore } from "@/store/notifications"
|
||||
|
||||
export function listNotifications() {
|
||||
return useNotificationStore.getState().notifications
|
||||
}
|
||||
import { httpJson } from "./http"
|
||||
|
||||
function isNotificationEnabled(type: Notification["type"]) {
|
||||
const prefs = useAuthStore.getState().notificationPrefs
|
||||
if (type === "order") return prefs.order
|
||||
if (type === "community") return prefs.community
|
||||
return prefs.system
|
||||
}
|
||||
|
||||
export function addNotification(input: {
|
||||
type: Notification["type"]
|
||||
title: string
|
||||
content: string
|
||||
link?: string
|
||||
}) {
|
||||
if (!isNotificationEnabled(input.type)) {
|
||||
return deny(400, "该类通知已关闭")
|
||||
type Paginated<T> = {
|
||||
items: T[]
|
||||
meta: {
|
||||
total: number
|
||||
offset: number
|
||||
limit: number
|
||||
}
|
||||
|
||||
useNotificationStore.getState().addNotification(input)
|
||||
return allow()
|
||||
}
|
||||
|
||||
export function markNotificationAsRead(notificationId: string) {
|
||||
useNotificationStore.getState().markAsRead(notificationId)
|
||||
export async function listNotifications(input?: {
|
||||
offset?: number
|
||||
limit?: number
|
||||
}): Promise<Notification[]> {
|
||||
const offset = input?.offset ?? 0
|
||||
const limit = input?.limit ?? 50
|
||||
|
||||
const searchParams = new URLSearchParams({
|
||||
offset: String(offset),
|
||||
limit: String(limit),
|
||||
})
|
||||
|
||||
const res = await httpJson<Paginated<Notification>>(`/api/v1/notifications?${searchParams}`, {
|
||||
cache: "no-store",
|
||||
})
|
||||
return res.items
|
||||
}
|
||||
|
||||
export async function markNotificationAsRead(notificationId: string): Promise<void> {
|
||||
await httpJson<unknown>(`/api/v1/notifications/${encodeURIComponent(notificationId)}/read`, {
|
||||
method: "PUT",
|
||||
cache: "no-store",
|
||||
})
|
||||
}
|
||||
|
||||
export async function markAllNotificationsAsRead(): Promise<void> {
|
||||
await httpJson<unknown>("/api/v1/notifications/read-all", {
|
||||
method: "PUT",
|
||||
cache: "no-store",
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user