zhaoyingbo b7437f47e4
All checks were successful
Egg CI/CD / build-image (push) Successful in 49s
Egg CI/CD / deploy (push) Successful in 23s
feat: 优化请求处理 & 拆分Type
2024-06-08 09:15:14 +00:00

106 lines
3.0 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 service from "../../services";
import { LarkServer, MsgProxy } from "../../types";
const validateMessageReq = (body: MsgProxy.Body) => {
if (!body.group_id && !body.receive_id) {
return new Response("group_id or receive_id is required", { status: 400 });
}
if (body.receive_id && !body.receive_id_type) {
return new Response("receive_id_type is required", { status: 400 });
}
if (!body.msg_type) {
return new Response("msg_type is required", { status: 400 });
}
if (!body.content) {
return new Response("content is required", { status: 400 });
}
return false;
};
export const manageMessageReq = async (req: Request) => {
const body = (await req.json()) as MsgProxy.Body;
// 校验参数
const validateRes = validateMessageReq(body);
if (validateRes) return validateRes;
// 遍历所有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 finalContent =
typeof body.content !== "string"
? JSON.stringify(body.content)
: body.content;
if (body.group_id) {
// 获取所有接收者
const group = await db.messageGroup.getOne(body.group_id!);
if (!group) {
return new Response("group not found", { status: 404 });
}
const { chat_id, open_id, union_id, user_id, email } = group;
// 构造发送消息函数
const makeSendFunc = (receive_id_type: LarkServer.ReceiveIDType) => {
return (receive_id: string) => {
sendList.push(
service.lark.message
.send(receive_id_type, receive_id, body.msg_type, finalContent)
.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"));
}
if (body.receive_id && body.receive_id_type) {
sendList.push(
service.lark.message
.send(
body.receive_id_type,
body.receive_id,
body.msg_type,
finalContent
)
.then((res) => {
sendRes[body.receive_id_type][body.receive_id] = res;
})
);
}
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,
});
}
};