Created
June 27, 2019 13:33
-
-
Save evilbuck/965bcc8d48bf5d1976b47e2d74a96853 to your computer and use it in GitHub Desktop.
Adapter pattern in javascript using data munging example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const v1Data = { | |
metrics: { | |
weightLb: 400, | |
heightFt: 6 | |
}, | |
macros: { | |
gramsFat: 1000 | |
} | |
}; | |
const v2Data = [400, 6, 1000]; | |
function fetchData() { | |
return axios.get(url); | |
} | |
function v1Adapter(data) { | |
return { | |
weightLb: data.metrics.weightLb, | |
heightFt: data.metrics.heightFt, | |
gramsFat: data.macros.gramsFat | |
}; | |
} | |
function v2Adapter(data) { | |
return { | |
weightLb: data[0], | |
heightFt: data[1], | |
gramsFat: data[2] | |
}; | |
} | |
function saveDataOrAnythingElse(data) { | |
this.setState({ d: adapter(data) }); | |
} | |
// save data with v1 format | |
fetchData() | |
.then(v1Adapter) | |
.then(saveDataOrAnythingElse); | |
// save data with v2 format | |
fetchData() | |
.then(v2Adapter) | |
.then(saveDataOrAnythingElse); | |
// The final output should always be the format: | |
// { weightLb, heightFt, gramsFat; } | |
// if we need to change the format, or the api return changes, | |
// then we only need to create a new adapter and plug that in. One thing to test | |
// and well separated from the rest of the code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment