I have a class called HtmlFile
which has a method called generate
. This method is responsible for generating an html file from handlebars template and data object provided in the HtmlFile
class constructor.
I am confused on what code design should I use for this use case and what variable names to choose.
class HtmlFile {
public file: any = null;
private template: any = null;
private data: any = null;
constructor(templatePath: string, params: any) {
this.template = path.resolve(templatePath);
this.data = params;
}
public async generate() {
try {
const error = this._validate();
if (error) {
throw error;
}
const fileContent = fs.readFileSync(this.template, "utf8");
const html = handlebars.compile(fileContent)(this.data);
return html;
} catch (e) {
throw e;
}
}
private _validate() {
let errStr: any = null;
if (typeof this.template !== "string") {
errStr = `expected template path to be a string, instead got
${typeof this.template}`;
}
if (typeof this.data !== "object") {
errStr = `expected data to be an object, instead got ${typeof
this.data}`;
}
return errStr;
}
}
And I am using this class in the following manner:
let htmlFile = new HtmlFile("./src/templates/sample.hbs", invoiceOptions);
const html: any = await htmlFile.generate();
return html;
I also want suggestions on what variable names I should use in place of htmlFile
and html
.