import { parseJsonString } from "@egg/hooks" import { LarkBody, LarkCard } from "@egg/lark-msg-tool" import loggerIns from "@egg/logger" import { LarkService, 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 } from "../services" import { Context } from "../types" // 获取所有应用信息 const appMap = parseJsonString(process.env.LARK_APP_MAP, {}) as Record< string, Context.APP_INFO > /** * 获取之前的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} 返回包含请求上下文的对象。 */ 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 = appMap[app] const requestId = getPreRequestId(larkBody) || uuid() const logger = loggerIns.child({ requestId }) const genResp = new NetTool({ requestId }) const larkService = new LarkService({ appId: appInfo.app_id, appSecret: appInfo.app_secret, 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, appMap, } as Context.Data } export default genContext