Files
juwan-frontend/lib/api/chat.ts
T

56 lines
1.9 KiB
TypeScript

import { allow, deny } from "@/lib/decision"
import { useAuthStore } from "@/store/auth"
import { useChatStore } from "@/store/chat"
export function listChatSessions() {
return useChatStore.getState().sessions
}
export function getChatSessionById(sessionId: string) {
return useChatStore.getState().sessions.find((session) => session.id === sessionId)
}
export function listChatMessages(sessionId: string) {
return useChatStore.getState().messages.filter((message) => message.sessionId === sessionId)
}
export function sendTextMessage(sessionId: string, content: string) {
const userId = useAuthStore.getState().user?.id
if (!userId) return deny(401, "请先登录")
const chatState = useChatStore.getState()
const session = chatState.sessions.find((item) => item.id === sessionId)
if (!session) return deny(404, "会话不存在")
if (session.readonly) return deny(400, "当前会话只读")
if (!session.participants.some((participant) => participant.id === userId)) {
return deny(403, "仅会话参与方可发送消息")
}
if (!content.trim()) {
return deny(400, "消息不能为空")
}
chatState.sendTextMessage(sessionId, userId, content)
return allow()
}
export function sendImageMessage(sessionId: string, imageUrl: string) {
const userId = useAuthStore.getState().user?.id
if (!userId) return deny(401, "请先登录")
const chatState = useChatStore.getState()
const session = chatState.sessions.find((item) => item.id === sessionId)
if (!session) return deny(404, "会话不存在")
if (session.readonly) return deny(400, "当前会话只读")
if (!session.participants.some((participant) => participant.id === userId)) {
return deny(403, "仅会话参与方可发送消息")
}
if (!imageUrl.trim()) {
return deny(400, "图片地址无效")
}
chatState.sendImageMessage(sessionId, userId, imageUrl)
return allow()
}