Translate external formats using adapters
Quick answer
An adapter translates an external interface or data format into a stable internal contract. Keep field-name conversions and protocol-specific failure handling at the edge instead of scattering them across business code.
How it works
A data adapter can validate a raw response and map fields to domain names. An interface adapter can wrap a function whose arguments differ from the application’s expectation. Reject incompatible data explicitly; do not silently invent missing identifiers. Use a small contract test for the mapping and a separate integration test for the actual provider.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {function adapt(x){if(typeof x.code!=="string"||!Number.isInteger(x.on_hand)||x.on_hand<0)throw new TypeError("record");return {id:x.code,qty:x.on_hand};}console.log(JSON.stringify(adapt({code:"A",on_hand:4,extra:9})));})()Expected console output:
{"id":"A","qty":4}The domain receives only its required field names and values.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const legacy=(id,count)=>`${id}:${count}`;const submit=({sku,qty})=>legacy(sku,qty);console.log(submit({sku:"B",qty:0}));})()Expected console output:
B:0The wrapper translates one object into two positional arguments, preserving zero.
Common mistakes
Do not pass the entire external object through unchanged when the domain expects a smaller, validated shape.
Practice
Adapt two suppliers with different quantity field names to one {id,qty} representation. Test the absence of a required field.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Translate external formats using adapters — Knowledge Check
Apply the concept and reason about local example output.
Which component should know an external provider’s field names?
What should an adapter do with a missing required identifier?
What test verifies a provider adapter’s actual compatibility?
What is the exact console output in Translate external formats using adapters example 1?
(async () => {function adapt(x){if(typeof x.code!=="string"||!Number.isInteger(x.on_hand)||x.on_hand<0)throw new TypeError("record");return {id:x.code,qty:x.on_hand};}console.log(JSON.stringify(adapt({code:"A",on_hand:4,extra:9})));})()What is the exact console output in Translate external formats using adapters example 2?
(async () => {const legacy=(id,count)=>`${id}:${count}`;const submit=({sku,qty})=>legacy(sku,qty);console.log(submit({sku:"B",qty:0}));})()