zhaoyingbo cabc23ae77
Some checks are pending
Egg CI/CD / build-image (push) Waiting to run
Egg CI/CD / deploy (push) Blocked by required conditions
feat: 支持根据用户组转发消息
2024-03-04 12:01:14 +00:00

83 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import db from "../../db";
import { sendMsg } from "../../utils/sendMsg";
interface MessageReqJson {
group_id: string;
msg_type: MsgType;
content: string;
}
const validateMessageReq = (body: MessageReqJson) => {
if (!body.group_id) {
return new Response("group_id is required");
}
if (!body.msg_type) {
return new Response("msg_type is required");
}
if (!body.content) {
return new Response("content is required");
}
return false;
};
export const manageMessageReq = async (req: Request) => {
const body = (await req.json()) as MessageReqJson;
// 校验参数
const validateRes = validateMessageReq(body);
if (validateRes) {
return validateRes;
}
// 获取所有接收者
const group = (await db.messageGroup.getOne(body.group_id)) as PBMessageGroup;
if (!group) {
return new Response("group not found");
}
const { chat_id, open_id, union_id, user_id, email } = group;
// 遍历所有id发送消息保存所有对应的messageId
const sendRes = {
chat_id: {} as Record<string, any>,
open_id: {} as Record<string, any>,
union_id: {} as Record<string, any>,
user_id: {} as Record<string, any>,
email: {} as Record<string, any>,
};
// 发送消息列表
const sendList = [] as Promise<any>[];
// 构造发送消息函数
const makeSendFunc = (receive_id_type: ReceiveIDType) => {
return (receive_id: string) => {
sendList.push(
sendMsg(receive_id_type, receive_id, body.msg_type, body.content).then(
(res) => {
sendRes[receive_id_type][receive_id] = res;
}
)
);
};
};
// 发送消息
if (chat_id) chat_id.map(makeSendFunc("chat_id"));
if (open_id) open_id.map(makeSendFunc("open_id"));
if (union_id) union_id.map(makeSendFunc("union_id"));
if (user_id) user_id.map(makeSendFunc("user_id"));
if (email) email.map(makeSendFunc("email"));
try {
await Promise.all(sendList);
return Response.json({
code: 200,
msg: "ok",
data: sendRes,
});
} catch {
return Response.json({
code: 400,
msg: "send msg failed",
data: sendRes,
});
}
};