Created
November 17, 2015 15:53
-
-
Save gitnik/6afe9dd896ffe4c3f5ca to your computer and use it in GitHub Desktop.
Frontend <-> Backend Mapping
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 default class HeardModel extends AbstractModel { | |
@ApiField('ApiConfidence') | |
private confidence: string = ''; | |
@ApiField('heardType') | |
private type: string = ''; | |
@ApiField('tradedOnDate', (dateString: string) => new Date(dateString), (date: Date) => date.getTime()) | |
private traded: Date = new Date(); | |
} | |
export default abstract class AbstractModel { | |
abstract fromApi(object) { | |
_.forEach(this.apiFieldsBag, (fieldObject, key) => { | |
this[key] = fieldObject.setFn(object[fieldObject.apiKey]); | |
}); | |
} | |
abstract toApi() { | |
const ret = {}; | |
_.forEach(this.apiFieldsBag, (fieldObject, key) => { | |
ret[fieldObject.apiKey] = fieldObject.getFn(this[key]); | |
}); | |
return ret; | |
} | |
} | |
export default function ApiField(apiKey: string, setFn, getFn) { | |
return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => { | |
target.apiFieldsBag = target.apiFieldsBag || {}; | |
target.apiFieldsBag[propertyKey] = { | |
apiKey: apiKey, | |
setFn: setFn || ((ret) => ret), | |
getFn: getFn || ((ret) => ret) | |
}; | |
return descriptor; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment