Solution: Shape Legacy API Responses Without Touching the Source
Explore how to use the Proxy pattern to intercept and transform property accesses on legacy API responses. You will learn to create a translation layer that maps outdated field names to modern ones without modifying the original object. This lesson helps you maintain compatibility while accessing data with consistent naming.
We'll cover the following...
Solution explanation
Lines 2–6: We define the
legacyUserobject that simulates a response from an outdated API.Its keys use old naming conventions (
fname,lname).We’ll adapt these keys to modern equivalents without altering this object.
Lines 9–23: The
createApiAdapter()function constructs a Proxy that provides this translation layer.A
mappingobject defines how modern names map to legacy keys.The
handlerobject contains aget()trap to intercept property access. ...