Last active
June 19, 2019 04:32
-
-
Save codeBelt/eacb3a2b82b1b0bb4be9ce634e7f7700 to your computer and use it in GitHub Desktop.
For Medium Article: https://medium.com/swlh/protect-your-javascript-applications-from-api-data-401a73c7c80b
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
import LocationModel from './LocationModel'; | |
import CarModel from './CarModel'; | |
class PersonModel { | |
firstName = ''; | |
lastName = ''; | |
age = 0; | |
address = null | |
cars = []; | |
/* | |
* firstName & lastName will be an empty string if there is no data. | |
* age will be zero if there is no data | |
* address will be a new LocationModel or null if there is no data | |
* cars will be an array of CarModel's or an empty array if there is no data | |
*/ | |
constructor(data) { | |
this.firstName = data.firstName || ''; | |
this.lastName = data.lastName || ''; | |
this.age = isNaN(data.age) ? 0 : data.age; | |
this.address = data.address ? new LocationModel(data.address) : null; | |
this.cars = this._safelyCreateArrayData(data.cars, CarModel); | |
} | |
_safelyCreateArrayData(dataForArray, Model) { | |
// if dataForArray is undefined or null, return empty array | |
if (dataForArray == null) { | |
return []; | |
} | |
// if dataForArray is a valid array, create array of models | |
if (Array.isArray(dataForArray)) { | |
return dataForArray.map((model) => new Model(model)) | |
} | |
// if dataForArray is a single object, create a model and return an array | |
return [ | |
new Model(dataForArray) | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment