79 lines
2.5 KiB
TypeScript
79 lines
2.5 KiB
TypeScript
import logger from "@egg/logger"
|
||
|
||
import initAppConfig from "./constant/config"
|
||
import { manageBotReq } from "./routes/bot"
|
||
import { manageMessageReq } from "./routes/message"
|
||
import { manageMicroAppReq } from "./routes/microApp"
|
||
import { manageModelProxyReq } from "./routes/modelProxy"
|
||
import { manageSheetReq } from "./routes/sheet"
|
||
import { initSchedule } from "./schedule"
|
||
import genContext from "./utils/genContext"
|
||
|
||
initSchedule()
|
||
|
||
await initAppConfig()
|
||
|
||
const bunServer = Bun.serve({
|
||
fetch: async (req, server) => {
|
||
// 设置超时时间
|
||
server.timeout(req, 30)
|
||
// 生成上下文
|
||
const ctx = await genContext(req)
|
||
const { path, genResp, logger } = ctx
|
||
// 非健康检查由打印必要信息
|
||
if (
|
||
path.exact("/bot") ||
|
||
path.exact("/message") ||
|
||
path.exact("/sheet") ||
|
||
path.startsWith("/micro_app")
|
||
) {
|
||
// 使用结构化日志,适合JSON模式
|
||
logger.info("收到请求", {
|
||
method: req.method,
|
||
url: req.url,
|
||
})
|
||
logger.debug("请求体内容", {
|
||
body: ctx.text,
|
||
})
|
||
}
|
||
// 逻辑处理
|
||
try {
|
||
// 机器人
|
||
if (path.exact("/bot")) return await manageBotReq(ctx)
|
||
// 消息代理发送
|
||
if (path.exact("/message")) return await manageMessageReq(ctx)
|
||
// 表格代理操作
|
||
if (path.exact("/sheet")) return await manageSheetReq(ctx)
|
||
// 小程序
|
||
if (path.startsWith("/micro_app")) return await manageMicroAppReq(ctx)
|
||
// 转发到模型代理服务
|
||
if (path.startsWith("/v1")) return manageModelProxyReq(ctx)
|
||
// 健康检查
|
||
if (path.full("/health")) return genResp.healthCheck()
|
||
// 错误模拟
|
||
if (path.startsWith("/mock/400")) return genResp.badRequest("模拟错误400")
|
||
if (path.startsWith("/mock/403")) return genResp.forbidden("模拟错误403")
|
||
if (path.startsWith("/mock/404")) return genResp.notFound("模拟错误404")
|
||
if (path.startsWith("/mock/500"))
|
||
return genResp.serverError("模拟错误500")
|
||
|
||
// 其他
|
||
return genResp.healthCheck("hello, there is egg, glade to serve you!")
|
||
} catch (error: any) {
|
||
// 错误处理
|
||
logger.error("服务器错误", {
|
||
message: error.message,
|
||
stack: error.stack,
|
||
})
|
||
return genResp.serverError(error.message || "server error")
|
||
}
|
||
},
|
||
port: 3000,
|
||
})
|
||
|
||
// 使用结构化日志记录服务启动信息
|
||
logger.info("服务器启动", {
|
||
hostname: bunServer.hostname,
|
||
port: bunServer.port,
|
||
})
|