Skip to content

Instantly share code, notes, and snippets.

@lansana
Last active May 17, 2017 23:30
Show Gist options
  • Save lansana/ac11a2148b6183d4ec45d642cdeda816 to your computer and use it in GitHub Desktop.
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.
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