egg_server/db/chat/index.ts

107 lines
2.3 KiB
TypeScript

import { RecordModel } from "pocketbase"
import { Context } from "../../types"
import { managePbError } from "../../utils/pbTools"
import pbClient from "../pbClient"
const DB_NAME = "chat"
export interface Chat {
chatId: string
name: string
avatar: string
mode: "group" | "p2p" | "topic"
weeklySummary: boolean
dailySummary: boolean
}
export type ChatModel = Chat & RecordModel
/**
* 获取单个群组信息
* @param id
* @returns
*/
const getOneByChatId = (chatId: string) =>
managePbError<ChatModel>(() =>
pbClient.collection(DB_NAME).getFirstListItem(`chatId = "${chatId}"`)
)
/**
* 创建群组
* @param chat
* @returns
*/
const create = (chat: Chat) =>
managePbError<ChatModel>(() => pbClient.collection(DB_NAME).create(chat))
/**
* 获取并创建群组
* @param chatId
* @param context
* @returns
*/
const getAndCreate = async ({ larkService, logger, larkBody }: Context) => {
const { chatId } = larkBody
if (!chatId) {
logger.error(`chatId is empty`)
return null
}
const chat = await getOneByChatId(chatId)
if (chat) return chat
logger.info(`chat ${chatId} not found, try to get from lark`)
const chatInfo = await larkService.chat.getChatInfo(chatId)
if (!chatInfo || chatInfo.code !== 0) return null
const { name, avatar, chat_mode } = chatInfo.data
const newChat = {
chatId,
name,
avatar,
mode: chat_mode,
weeklySummary: false,
dailySummary: false,
}
return create(newChat)
}
/**
* 更新群组总结
* @param id
* @param timeScope
* @param value
* @returns
*/
const updateSummary = async (
id: string,
timeScope: "daily" | "weekly",
value: boolean
) =>
managePbError<ChatModel>(() =>
pbClient.collection(DB_NAME).update(id, { [`${timeScope}Summary`]: value })
)
/**
* 获取需要总结的群组
* @param timeScope
* @returns
*/
const getNeedSummaryChats = async (timeScope: "daily" | "weekly" | "all") => {
const filterMap = {
daily: "dailySummary = true",
weekly: "weeklySummary = true",
all: "dailySummary = true && weeklySummary = true",
}
return managePbError<ChatModel[]>(() =>
pbClient.collection(DB_NAME).getFullList({ filter: filterMap[timeScope] })
)
}
const chat = {
getAndCreate,
getOneByChatId,
updateSummary,
getNeedSummaryChats,
}
export default chat