Last active
May 17, 2017 23:30
-
-
Save lansana/ac11a2148b6183d4ec45d642cdeda816 to your computer and use it in GitHub Desktop.
TypeScript JSON decorator to turn convert ES6 class properties from camelCaseLikeThis to snake_case_like_this to be used as an HTTP request JSON object.
This file contains hidden or 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
function JSON<T extends {new(...args: any[]): {}}>(ctor: T) { | |
function toSnakeCase(prop: string): string { | |
return prop.replace(/[A-Z]/g, (prop: string): string => { | |
return `_${prop.toLowerCase()}`; | |
}); | |
} | |
return class extends ctor { | |
constructor(...args: any[]) { | |
let cfg = args.shift(); | |
for (let prop in cfg) { | |
if (Object.prototype.hasOwnProperty.call(cfg, prop)) { | |
cfg[toSnakeCase(prop)] = cfg[prop]; | |
delete cfg[prop]; | |
} | |
} | |
super(cfg, ...args); | |
} | |
} | |
} | |
@JSON | |
class Person { | |
id: number; | |
firstName: string; | |
lastName: string; | |
homePhoneNumber: string; | |
cellPhoneNumber: string; | |
constructor(values: Object = {}) { | |
Object.assign(this, values); | |
} | |
} | |
let snake_case_json_object = new Person({ | |
id: 0, | |
firstName: 'John', | |
lastName: 'Doe', | |
homePhoneNumber: '1-800-555-1337', | |
cellPhoneNumber: '1-800-555-1337' | |
}); | |
console.log(snake_case_json_object); | |
// { | |
// "first_name": "John", | |
// "last_name": "Doe", | |
// "home_phone_number": "1-800-555-1337", | |
// "cell_phone_number": "1-800-555-1337", | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment