Last active
October 14, 2020 18:13
-
-
Save azamanaza/be3cce274d956f94c6ef3a151df28257 to your computer and use it in GitHub Desktop.
An extensible base model class
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
export class BaseModel { | |
protected properties: string[]; | |
protected relationships: string[] = []; | |
constructor(data: any, properties: string[], relationships: string[] = []) { | |
if (!!data) { | |
Object.keys(data).forEach(key => { | |
this[key] = data[key]; | |
}); | |
} | |
this.properties = properties; | |
this.relationships = relationships; | |
} | |
toJson(includeRelations = true): {[key: string]: any} { | |
// get own props | |
const json = this.properties.reduce((acc, prop) => ({ ...acc, [prop]: this[prop] }), {}); | |
return { | |
...json, | |
...(includeRelations ? this.relationshipsToJson() : {}) | |
}; | |
} | |
protected mapPropsToInt(props: string[]): void { | |
if (!!props) { | |
props.forEach(name => { | |
if (this.hasOwnProperty(name)) { | |
this[name] = (!!this[name] || this[name] === '0') ? +this[name] : 0; | |
} | |
}); | |
} | |
} | |
protected mapPropToModel(prop: string, Model: any): void { | |
if (this.hasOwnProperty(prop)) { | |
this[prop] = (!!this[prop]) ? new Model(this[prop]) : undefined; | |
} | |
} | |
private relationshipsToJson(): {[key: string]: any} { | |
if (this.relationships.length === 0) { | |
return {}; | |
} | |
return this.relationships.reduce((acc, key) => { | |
const rel = this[key]; | |
if (!! rel) { | |
acc[key] = Array.isArray(rel) ? rel.map(item => item.toJson()) : rel.toJson(); | |
} | |
return acc; | |
}, {}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment