egg_attach_template/utils/genContext.ts

52 lines
1.1 KiB
TypeScript

import loggerIns from "@egg/logger"
import { NetTool } from "@egg/net-tool"
import { PathCheckTool } from "@egg/path-tool"
import { v4 as uuid } from "uuid"
import { Logger } from "winston"
export interface Context {
req: Request
requestId: string
logger: Logger
genResp: NetTool
body: any
text: string
path: PathCheckTool
searchParams: URLSearchParams
}
/**
* 生成请求上下文。
*
* @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 searchParams = new URL(req.url).searchParams
const requestId = uuid()
const logger = loggerIns.child({ requestId })
const genResp = new NetTool({ requestId })
const path = new PathCheckTool(req.url)
return {
req,
path,
requestId,
logger,
genResp,
body,
text,
searchParams,
} as Context
}
export default genContext