Solution: Track API Usage Metrics Transparently
Use the get trap to wrap each method call and count invocations transparently.
We'll cover the following...
We'll cover the following...
Solution explanation
Lines 2–10: We define the
ApiServiceclass that simulates two operations:fetchData()andpostData().These represent typical API calls whose usage frequency we want to monitor.
The goal is to track calls externally without changing the service implementation.
Lines 13–37: The
createTrackedService()function constructs a Proxy that adds a transparent tracking layer.A
targetinstance ofApiServiceis created as the real object.A
statsobject stores call counts per method name. ...