Search⌘ K
AI Features

Solution: Inject Configuration into a Decorator

Explore how to enhance Node.js functions with dynamic logging by creating a configurable decorator factory. Understand how to wrap both synchronous and asynchronous functions to log messages with context-specific prefixes without altering the original logic.

Solution explanation

  • Lines 2–6: We define fetchOrder, a mock async function representing a service call. It resolves with an order object after a short delay.

  • Lines 9–18: We create createLogger(prefix), a decorator factory.

    • It accepts a prefix string and returns a new decorator function.

    • That decorator wraps any target function and logs both before and after ...