62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import logger from "@/utils/logger"
|
|
|
|
/**
|
|
* Wraps an async function with logging for start, completion, and errors.
|
|
* Accepts positional parameters like findEach.
|
|
*/
|
|
function withLoggingFactory(
|
|
description: string,
|
|
wrappedFunction: () => Promise<void>
|
|
): () => Promise<void>
|
|
|
|
function withLoggingFactory<T extends Record<string, unknown>>(
|
|
description: string,
|
|
context: T,
|
|
wrappedFunction: (context: T) => Promise<void>
|
|
): () => Promise<void>
|
|
|
|
function withLoggingFactory<T extends Record<string, unknown>>(
|
|
description: string,
|
|
contextOrFunction?: T | (() => Promise<void>),
|
|
wrappedFunction?: (context: T) => Promise<void>
|
|
): () => Promise<void> {
|
|
// 2-argument version: (description, wrappedFunction)
|
|
if (typeof contextOrFunction === "function") {
|
|
return async () => {
|
|
logger.info(`Starting: ${description}`)
|
|
|
|
try {
|
|
await contextOrFunction()
|
|
logger.info(`Completed: ${description}`)
|
|
} catch (error) {
|
|
logger.error(`Failed: ${description}`, { error })
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3-argument version: (description, context, wrappedFunction)
|
|
if (typeof contextOrFunction !== "object") {
|
|
throw new Error("Missing context")
|
|
}
|
|
const context: T = contextOrFunction
|
|
|
|
if (typeof wrappedFunction !== "function") {
|
|
throw new Error("Missing wrapped function")
|
|
}
|
|
|
|
return async () => {
|
|
logger.info(`Starting: ${description} with ${context}`, { context })
|
|
|
|
try {
|
|
await wrappedFunction(context)
|
|
logger.info(`Completed: ${description} with ${context}`, { context })
|
|
} catch (error) {
|
|
logger.error(`Failed: ${description} with ${context}`, { context, error })
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
export default withLoggingFactory
|