Skip to content

Instantly share code, notes, and snippets.

@gitnik
Created November 17, 2015 15:53
Show Gist options
  • Save gitnik/6afe9dd896ffe4c3f5ca to your computer and use it in GitHub Desktop.
Save gitnik/6afe9dd896ffe4c3f5ca to your computer and use it in GitHub Desktop.
Frontend <-> Backend Mapping
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