Skip to content

Instantly share code, notes, and snippets.

@azamanaza
Last active October 14, 2020 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azamanaza/be3cce274d956f94c6ef3a151df28257 to your computer and use it in GitHub Desktop.
Save azamanaza/be3cce274d956f94c6ef3a151df28257 to your computer and use it in GitHub Desktop.
An extensible base model class
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