egg_server/utils/genContext.ts
zhaoyingbo d64d6211c0
All checks were successful
Egg Server CI/CD / build-image (push) Successful in 50s
Egg Server CI/CD / refresh-image (push) Successful in 12s
Egg Server CI/CD / fast-deploy (push) Successful in 3s
feat(group-agent): 支持大模型语义化理解用户输入
2024-10-16 12:20:25 +00:00

77 lines
1.9 KiB
TypeScript

import { LarkBody, LarkCard } from "@egg/lark-msg-tool"
import loggerIns from "@egg/logger"
import { NetTool } from "@egg/net-tool"
import { PathCheckTool } from "@egg/path-tool"
import { v4 as uuid } from "uuid"
import cardMap from "../constant/card"
import functionMap from "../constant/function"
import tempMap from "../constant/template"
import { AttachService, LarkService } from "../services"
import { Context } from "../types"
/**
* 获取之前的requestId。
*
* @param larkBody - 请求体。
* @returns 返回之前的requestId。
*/
const getPreRequestId = (larkBody: LarkBody) => {
// 在Action请求中会带上之前的requestId
const value = larkBody.actionValue
if (!value || !value.requestId) return ""
return value.requestId
}
/**
* 生成请求上下文。
*
* @param {Request} req - 请求对象。
* @returns {Promise<Context.Data>} 返回包含请求上下文的对象。
*/
const genContext = async (req: Request) => {
let body: any = null
let text: string = ""
try {
text = await req.text()
body = JSON.parse(text)
} catch {
/* empty */
}
const larkBody = new LarkBody(body)
const searchParams = new URL(req.url).searchParams
const app = searchParams.get("app") || "egg"
const requestId = getPreRequestId(larkBody) || uuid()
const logger = loggerIns.child({ requestId })
const genResp = new NetTool({ requestId })
const larkService = new LarkService(app, requestId)
const attachService = new AttachService({ requestId })
const path = new PathCheckTool(req.url)
const larkCard = new LarkCard(
"egg",
false,
requestId,
cardMap,
tempMap,
functionMap
)
return {
req,
path,
requestId,
logger,
genResp,
body,
text,
larkService,
larkBody,
larkCard,
attachService,
searchParams,
app,
} as Context.Data
}
export default genContext