Skip to content

Instantly share code, notes, and snippets.

@pranavrajs
Created October 18, 2017 12:03
Show Gist options
  • Save pranavrajs/57f13320fecae6b49c5c48620d8c0449 to your computer and use it in GitHub Desktop.
Save pranavrajs/57f13320fecae6b49c5c48620d8c0449 to your computer and use it in GitHub Desktop.
Template Generator
const template = require('./template.json');
class TemplateGenerator {
constructor(template, prefix = '') {
if (!template) {
throw new Error('Template is required');
}
this.prefix = prefix;
this.template = template;
}
isPrimitive(attr) {
return typeof attr === 'string' || typeof attr === 'number';
}
isNull(attr) {
return attr === null || attr === undefined;
}
generateTemplate(keyPrefix, templateJson) {
if (this.isPrimitive(templateJson)) {
return typeof templateJson;
}
const keys = Object.keys(templateJson);
const templateObj = {};
keys.forEach(key => {
const value = templateJson[key];
const newKey = `${keyPrefix}${ key !== '_id' ? '_' : '' }${key}`;
if (this.isPrimitive(value)) {
if (typeof value === 'number' && value > 32768) {
templateObj[newKey] = 'double';
} else {
templateObj[newKey] = typeof value;
}
} else if (this.isNull(value)) {
templateObj[newKey] = 'string';
} else if (value instanceof Array && value.length) {
templateObj[newKey] = [this.generateTemplate(newKey, value[0])];
} else if (typeof value === 'object') {
templateObj[newKey] = this.generateTemplate(newKey, value);
}
});
return templateObj;
}
generate() {
const { prefix, template } = this;
return this.generateTemplate(prefix, template);
}
}
const templateObj = new TemplateGenerator(template, '__')
console.log(JSON.stringify(templateObj.generate()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment