feat(logger): 重构服务构造函数以使用 Logger,移除 requestId 参数

This commit is contained in:
zhaoyingbo 2025-04-03 13:31:28 +00:00
parent 8cf6d244b2
commit 308b447cbc
10 changed files with 128 additions and 87 deletions
packages
lark-msg-tool/src/larkCard
net-tool/src
test

@ -1,4 +1,3 @@
import logger from "@egg/logger"
import _, { isObject } from "lodash"
import { Logger } from "winston"
@ -26,14 +25,23 @@ class LarkCard<
protected stringify: boolean
protected logger: Logger
constructor(
funcName: string,
stringify: boolean,
requestId: string,
cardMap: TCardMap,
tempMap: TTempMap,
functionMap: TFunctionMap
) {
constructor({
funcName,
stringify = false,
requestId,
cardMap = {} as TCardMap,
tempMap = {} as TTempMap,
functionMap = {} as TFunctionMap,
logger,
}: {
funcName: string
stringify: boolean
requestId: string
cardMap?: TCardMap
tempMap?: TTempMap
functionMap?: TFunctionMap
logger: Logger
}) {
this.stringify = stringify
this.requestId = requestId
this.funcName = funcName
@ -45,7 +53,7 @@ class LarkCard<
...cardMap,
}
this.tempMap = tempMap
this.logger = logger.child({ requestId })
this.logger = logger
}
setFunction(funcName: string) {
@ -57,20 +65,23 @@ class LarkCard<
}
child(func: string, stringify?: boolean) {
return new LarkCard(
func,
stringify || this.stringify,
this.requestId,
this.cardMap,
this.tempMap,
this.functionMap
)
return new LarkCard({
funcName: func,
stringify: stringify || this.stringify,
requestId: this.requestId,
cardMap: this.cardMap,
tempMap: this.tempMap,
functionMap: this.functionMap,
logger: this.logger,
})
}
genCard(cardKey: keyof TCardMap | object, variables: { [key: string]: any }) {
const card = isObject(cardKey) ? cardKey : this.cardMap[cardKey]
if (!card) {
this.logger.error(`Card ${String(cardKey)} not found`)
this.logger.error("卡片未找到", {
cardKey: String(cardKey),
})
throw new Error(`Card ${String(cardKey)} not found`)
}
const finalVariables: Record<string, any> = {
@ -78,9 +89,10 @@ class LarkCard<
requestId: this.requestId,
...this.functionMap[this.funcName],
}
this.logger.debug(
`Card ${String(cardKey)} final variables: ${JSON.stringify(finalVariables)}`
)
this.logger.debug("卡片最终变量", {
cardKey: String(cardKey),
variables: finalVariables,
})
const replaceVariables = (str: string): string => {
const variablePattern = /\$\{(\w+)\}/g
@ -125,9 +137,10 @@ class LarkCard<
const finalContent = injectVariables(content)
this.logger.debug(
`Card ${String(cardKey)} final content: ${JSON.stringify(finalContent)}`
)
this.logger.debug("卡片最终内容", {
cardKey: String(cardKey),
content: finalContent,
})
return this.stringify ? JSON.stringify(finalContent) : finalContent
}
@ -146,7 +159,9 @@ class LarkCard<
genTempCard(tempKey: keyof TTempMap, variables: { [key: string]: any }) {
const tempId = this.tempMap[tempKey]
if (!tempId) {
this.logger.error(`Temp ${String(tempKey)} not found`)
this.logger.error("模板未找到", {
tempKey: String(tempKey),
})
throw new Error(`Temp ${String(tempKey)} not found`)
}
const finalVariables: Record<string, any> = {
@ -154,9 +169,10 @@ class LarkCard<
requestId: this.requestId,
...this.functionMap[this.funcName],
}
this.logger.debug(
`Temp ${String(tempKey)} final variables: ${JSON.stringify(finalVariables)}`
)
this.logger.debug("模板最终变量", {
tempKey: String(tempKey),
variables: finalVariables,
})
const content = {
type: "template",
data: {
@ -168,9 +184,10 @@ class LarkCard<
template_variable: finalVariables,
},
}
this.logger.debug(
`Temp ${String(tempKey)} final content: ${JSON.stringify(content)}`
)
this.logger.debug("模板最终内容", {
tempKey: String(tempKey),
content,
})
return this.stringify ? JSON.stringify(content) : content
}
}

@ -1,14 +1,16 @@
import { Logger } from "winston"
import NetToolBase from "../netTool/base"
import type { Gitlab } from "../types"
class GitlabBaseService extends NetToolBase {
public project_id: number = 0;
public merge_request_iid: number = 0;
public project_id: number = 0
public merge_request_iid: number = 0
constructor(baseUrl: string, authKey: string, requestId: string) {
constructor(baseUrl: string, authKey: string, logger: Logger) {
super({
prefix: baseUrl,
requestId,
logger,
headers: { "PRIVATE-TOKEN": authKey },
})
}

@ -1,3 +1,5 @@
import loggerIns from "@egg/logger"
import Badge from "./badge"
import Commit from "./commit"
import Discussions from "./discussions"
@ -23,26 +25,26 @@ class GitlabService {
* GitLab
* @param {string} baseUrl - GitLab URL
* @param {string} authKey -
* @param {string} requestId - ID
* @param {string} logger -
*/
constructor({
baseUrl = "",
authKey = "",
requestId = "",
logger = loggerIns,
}: {
baseUrl?: string
authKey?: string
requestId?: string
logger?: any
}) {
this.badge = new Badge(baseUrl, authKey, requestId)
this.commit = new Commit(baseUrl, authKey, requestId)
this.discussions = new Discussions(baseUrl, authKey, requestId)
this.mergeRequests = new MergeRequests(baseUrl, authKey, requestId)
this.notes = new Notes(baseUrl, authKey, requestId)
this.pipelines = new Pipelines(baseUrl, authKey, requestId)
this.project = new Project(baseUrl, authKey, requestId)
this.repository = new Repository(baseUrl, authKey, requestId)
this.hook = new Hook(baseUrl, authKey, requestId)
this.badge = new Badge(baseUrl, authKey, logger)
this.commit = new Commit(baseUrl, authKey, logger)
this.discussions = new Discussions(baseUrl, authKey, logger)
this.mergeRequests = new MergeRequests(baseUrl, authKey, logger)
this.notes = new Notes(baseUrl, authKey, logger)
this.pipelines = new Pipelines(baseUrl, authKey, logger)
this.project = new Project(baseUrl, authKey, logger)
this.repository = new Repository(baseUrl, authKey, logger)
this.hook = new Hook(baseUrl, authKey, logger)
}
/**

@ -1,3 +1,5 @@
import { Logger } from "winston"
import NetToolBase, { NetError } from "../netTool/base"
import { Lark } from "../types"
export class LarkAuthService extends NetToolBase {
@ -7,18 +9,18 @@ export class LarkAuthService extends NetToolBase {
constructor({
appId,
appSecret,
requestId,
logger,
}: {
appId?: string
appSecret?: string
requestId: string
logger?: Logger
}) {
super({
prefix:
process.env.NODE_ENV === "production"
? "http://lark-auth.c5-cloudml.xiaomi.srv/lark_auth"
: "http://lark-auth.staging-cloudml.xiaomi.srv/lark_auth",
requestId,
logger,
})
this.appId = appId || process.env.LARK_APP_ID || ""
this.appSecret = appSecret || process.env.LARK_APP_SECRET || ""

@ -1,11 +1,12 @@
import { Logger } from "winston"
import NetToolBase, { NetError } from "../netTool/base"
class LarkBaseService extends NetToolBase {
constructor(getToken: () => Promise<string>, requestId: string) {
constructor(getToken: () => Promise<string>, logger?: Logger) {
super({
prefix: "https://open.f.mioffice.cn/open-apis",
requestId,
logger,
getHeaders: async () => ({
Authorization: `Bearer ${await getToken()}`,
}),
@ -26,6 +27,4 @@ class LarkBaseService extends NetToolBase {
}
}
export default LarkBaseService

@ -1,3 +1,5 @@
import { Logger } from "winston"
import LarkAuthService from "./auth"
import LarkChatService from "./chat"
import LarkDriveService from "./drive"
@ -14,30 +16,28 @@ class LarkService {
auth: LarkAuthService
chat: LarkChatService
wiki: LarkWikiService
requestId: string
constructor({
appId,
appSecret,
requestId,
logger,
}: {
appId?: string
appSecret?: string
requestId: string
logger?: Logger
}) {
this.auth = new LarkAuthService({
appId,
appSecret,
requestId,
logger,
})
const getAppAuth = () => this.auth.getAppAuth()
this.drive = new LarkDriveService(getAppAuth, requestId)
this.message = new LarkMessageService(getAppAuth, requestId)
this.user = new LarkUserService(getAppAuth, requestId)
this.sheet = new LarkSheetService(getAppAuth, requestId)
this.chat = new LarkChatService(getAppAuth, requestId)
this.wiki = new LarkWikiService(getAppAuth, requestId)
this.requestId = requestId
this.drive = new LarkDriveService(getAppAuth, logger)
this.message = new LarkMessageService(getAppAuth, logger)
this.user = new LarkUserService(getAppAuth, logger)
this.sheet = new LarkSheetService(getAppAuth, logger)
this.chat = new LarkChatService(getAppAuth, logger)
this.wiki = new LarkWikiService(getAppAuth, logger)
}
}

@ -1,4 +1,4 @@
import logger from "@egg/logger"
import loggerIns from "@egg/logger"
import { Logger } from "winston"
import { NetErrorDetail, NetRequestParams } from "../types"
@ -26,7 +26,6 @@ class NetToolBase {
protected headers: Record<string, string>
protected getHeaders: () => Promise<Record<string, string>>
protected logger: Logger
protected requestId: string
/**
*
@ -35,24 +34,23 @@ class NetToolBase {
* @param {string} [params.prefix] - URL前缀
* @param {Record<string, string>} [params.headers] -
* @param {Function} [params.getHeaders] -
* @param {string} [params.requestId] - ID
* @param {Logger} [params.logger] -
*/
constructor({
prefix,
headers,
getHeaders,
requestId,
logger,
}: {
prefix?: string
headers?: Record<string, string>
getHeaders?: () => Promise<Record<string, string>>
requestId?: string
logger?: Logger
} = {}) {
this.prefix = prefix || ""
this.headers = headers || {}
this.getHeaders = getHeaders || (async () => ({}))
this.requestId = requestId || ""
this.logger = logger.child({ requestId })
this.logger = logger || loggerIns
}
/**
@ -62,25 +60,25 @@ class NetToolBase {
* @param {string} [params.prefix] - URL前缀
* @param {Record<string, string>} [params.headers] -
* @param {Function} [params.getHeaders] -
* @param {string} [params.requestId] - ID
* @param {Logger} [params.logger] -
* @returns
*/
child({
prefix,
headers,
getHeaders,
requestId,
logger,
}: {
prefix?: string
headers?: Record<string, string>
getHeaders?: () => Promise<Record<string, string>>
requestId?: string
logger?: Logger
} = {}) {
return new NetToolBase({
prefix: prefix || this.prefix,
headers: headers || this.headers,
getHeaders: getHeaders || this.getHeaders,
requestId: requestId || this.requestId,
logger: logger || this.logger,
})
}
@ -117,7 +115,7 @@ class NetToolBase {
requestTime,
responseTime: new Date().getTime(),
}
this.logger.silly(JSON.stringify(responseLog, null, 2))
this.logger.silly('')
return responseLog
}

@ -2,6 +2,35 @@ import { NetRequestParams } from "../types"
import NetToolBase from "./base"
class NetTool extends NetToolBase {
/**
* @description ID
*/
private requestId: string
/**
* @description NetTool类的构造函数
* @param {Object} params -
* @param {string} [params.prefix] - URL前缀
* @param {Record<string, string>} [params.headers] -
* @param {Function} [params.getHeaders] -
* @param {Logger} [params.logger] -
* @param {string} params.requestId - ID
*/
constructor({
prefix,
headers,
getHeaders,
logger,
requestId,
}: {
prefix?: string
headers?: Record<string, string>
getHeaders?: () => Promise<Record<string, string>>
logger?: any
requestId: string
}) {
super({ prefix, headers, getHeaders, logger })
this.requestId = requestId
}
public request<T = any>({
url,
method,

@ -1,11 +1,4 @@
export namespace Gitlab {
export interface InitParams {
baseUrl: string
requestId: string
authKey: string
project_id?: number
merge_request_iid?: number
}
/* 错误 */
export interface Error {
/**

@ -3,7 +3,6 @@ import { LarkService } from "../packages/net-tool/src/index"
const larkService = new LarkService({
appId: "appId",
appSecret: "appSecret",
requestId: "requestId",
})
larkService.user