UNPKG

@bitblit/ratchet-misc

Version:

Ratchet miscellaneous tooling that requires smallish dependant libraries

79 lines 3.1 kB
import handlebars from 'handlebars'; import fetch from 'cross-fetch'; import { Logger } from '@bitblit/ratchet-common/logger/logger'; import { StringRatchet } from '@bitblit/ratchet-common/lang/string-ratchet'; import layouts from 'handlebars-layouts'; export class RemoteHandlebarsTemplateRenderer { prefix; suffix; maxCacheTemplates; cache; constructor(prefix = '', suffix = '', maxCacheTemplates = 10) { this.prefix = prefix; this.suffix = suffix; this.maxCacheTemplates = maxCacheTemplates; if (this.maxCacheTemplates > 0) { this.cache = new Map(); } } async renderTemplate(templateName, context, layoutName = null) { return this.renderRemoteTemplate(templateName, context, layoutName); } async renderRemoteTemplate(templateName, inContext, layoutName = null) { const template = await this.fetchTemplate(templateName); const layoutText = layoutName ? await this.fetchTemplateText(layoutName) : null; if (layoutText) { await layouts.register(handlebars); handlebars.registerPartial(layoutName, layoutText); } const context = inContext || {}; const result = template ? template(context) : null; return result; } async renderTemplateDirect(templateText, context, layoutName = null) { const template = handlebars.compile(templateText); const result = template(context); return result; } async fetchTemplate(templateName) { let rval = null; try { if (!!this.cache && this.cache.has(templateName)) { Logger.silly('Cache hit for template : %s', templateName); rval = this.cache.get(templateName); } else { Logger.debug('Cache miss for template : %s', templateName); const templateText = await this.fetchTemplateText(templateName); if (templateText) { rval = handlebars.compile(templateText); if (!!this.cache && !!rval) { this.cache.set(templateName, rval); if (this.cache.size > this.maxCacheTemplates) { this.cache.delete(Array.from(this.cache.keys())[0]); } } } } } catch (err) { Logger.warn('Could not fetch and compile template : %s : %s', templateName, err, err); rval = null; } return rval; } async fetchTemplateText(templateName) { let rval = null; const url = StringRatchet.trimToEmpty(this.prefix) + templateName + StringRatchet.trimToEmpty(this.suffix); try { const resp = await fetch(url); rval = await resp.text(); } catch (err) { Logger.warn('Could not fetch url : %s : %s', url, err, err); rval = null; } return rval; } } //# sourceMappingURL=remote-handlebars-template-renderer.js.map