feat(logger): 重构服务构造函数以使用 Logger,移除 requestId 参数
All checks were successful
/ release (push) Successful in 33s

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,35 @@ import { NetRequestParams } from "../types"
import NetToolBase from "./base" import NetToolBase from "./base"
class NetTool extends NetToolBase { 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>({ public request<T = any>({
url, url,
method, method,

View File

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

View File

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