81 lines
2.0 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 { APP_MAP } from "../constant/config"
import functionMap from "../constant/function"
import tempMap from "../constant/template"
import { AttachService } from "../services"
import { Context } from "../types"
import genLarkService from "./genLarkService"
/**
* 获取之前的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>} 返回包含请求上下文的对象。
*/
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 appInfo = APP_MAP[app]
const requestId = getPreRequestId(larkBody) || uuid()
const logger = loggerIns.child({ requestId })
const genResp = new NetTool({ requestId })
const larkService = genLarkService("egg", 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,
appInfo,
} as Context
}
export default genContext