Solution: Compose Decorators Dynamically Based on Configuration
Explore how to implement reusable logging and timing decorators for async functions in Node.js. Learn to dynamically compose these decorators based on configuration without changing the base function, enabling environment-specific instrumentation for development, staging, and production.
We'll cover the following...
Solution explanation
Lines 2–6: We define
processOrder, a mock async service that simulates an order-processing delay. It represents our core business logic.Lines 9–16: We create
withLogging(fn)to add visibility:Logs the input arguments before execution.
Waits for the function result.
Logs the returned output afterward.
Returns the same result transparently.
Lines 19–27: We define
withTiming(fn)to measure performance:Records the start time before calling the wrapped function.
Awaits its completion. ...