egg_server/utils/genContext.ts
zhaoyingbo 09e352a9c1
All checks were successful
Egg Server MIflow / build-image (push) Successful in 1m5s
feat: 抽象网络请求类 & 内容转为ctx向内传递
2024-08-16 09:12:11 +00:00

43 lines
971 B
TypeScript

import { v4 as uuid } from "uuid"
import loggerIns from "../log"
import { AttachService, LarkService } from "../services"
import { Context } from "../types"
import NetTool from "./netTool"
/**
* 生成请求上下文。
*
* @param {Request} req - 请求对象。
* @returns {Promise<Context.Data>} 返回包含请求上下文的对象。
*/
const genContext = async (req: Request) => {
const requestId = uuid()
const logger = loggerIns.child({ requestId })
const genResp = new NetTool({ requestId })
const larkService = new LarkService("egg", requestId)
const attachService = new AttachService({ requestId })
let body: any = null
let text: string = ""
try {
text = await req.text()
body = JSON.parse(text)
} catch {
/* empty */
}
logger.debug(`req body: ${text}`)
return {
req,
requestId,
logger,
genResp,
body,
text,
larkService,
attachService,
} as Context.Data
}
export default genContext