UNPKG

alfred-bear

Version:

Alfred Workflow to handle bear templates

63 lines (62 loc) 1.98 kB
import Handlebars from "handlebars"; import fs from "fs"; import { BearTemplateError } from "./Error.js"; export class CompiledTemplate { constructor(templatePath) { this.templatePath = templatePath; } /** * Gets the variables in the form * ```json * { * "var": Record<string,string> * } * ``` * */ set variables(vars) { if (vars) this._variables = JSON.parse(vars).var; } set answer(answer) { this._answer = answer ? { answer: answer } : undefined; } async executeScript(scriptPath) { return new Promise(async (resolve, reject) => { try { const { default: script } = scriptPath ? await import(scriptPath) : { default: async () => ({}) }; const preScriptData = Object.assign(Object.assign({}, this._variables), this._answer); this._script = await script(preScriptData); resolve(); } catch (e) { reject(new BearTemplateError(`Could not load script file \`${scriptPath}\` \n\`\`\`${e}\n\`\`\``)); } }); } async compile() { return new Promise(async (resolve, reject) => { const data = this.data; try { const template = this.getCompiledTemplate(); resolve(template(data)); } catch (e) { reject(e); } }); } get data() { return Object.assign(Object.assign(Object.assign({}, this._script), this._variables), this._answer); } getCompiledTemplate() { try { const fileContent = fs.readFileSync(this.templatePath, "utf8"); return Handlebars.compile(fileContent); } catch (e) { throw new BearTemplateError(`Template file **${this.templatePath}** could not be found`); } } }