Files
azure-image-chooser/app/backend/src/template-service.ts

42 lines
1.1 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import nunjucks from "nunjucks";
import type { ImageSelection, UsageTemplate } from "./types";
const findAppRoot = (): string => {
const candidates = [join(__dirname, "../../.."), join(__dirname, "../..")];
for (const candidate of candidates) {
if (existsSync(join(candidate, "templates.json"))) {
return candidate;
}
}
throw new Error("Unable to resolve app template root");
};
export class TemplateService {
private readonly appRoot = findAppRoot();
private readonly env = nunjucks.configure(join(this.appRoot, "templates"), {
autoescape: false,
noCache: true
});
private readonly templates: UsageTemplate[] = JSON.parse(
readFileSync(join(this.appRoot, "templates.json"), "utf8")
) as UsageTemplate[];
public getTemplates(): UsageTemplate[] {
return this.templates;
}
public render(templateFile: string, selection: ImageSelection): string {
return this.env.render(templateFile, selection);
}
public buildSkuExport(skus: string[]): string {
return `[\n${skus.map((sku) => `\t\"${sku}\"`).join(",\n")}\n]`;
}
}