@opengis/fastify-table
Version:
core-plugins
85 lines (84 loc) • 3.25 kB
JavaScript
import path from "node:path";
import { readdirSync, readFileSync } from "node:fs";
import yaml from "js-yaml";
import getTemplatePath from "./getTemplatePath.js";
import loadTemplate from "./loadTemplate.js";
import mdToHTML from "../../md/funcs/mdToHTML.js";
function readFileData(file) {
const data = readFileSync(file, "utf-8");
const ext = file.substring(file.lastIndexOf(".") + 1);
if (ext === "yml") {
return yaml.load(data);
}
if (ext === "json") {
return JSON.parse(data);
}
if (ext === "md") {
const match = data.match(/^---\r?\n([\s\S]*?)---\r?\n([\s\S]*)$/);
const parseLinesRecursively = (lines, index = 0, result = {}) => index >= lines.length
? result
: (([key, ...rest]) => key && rest.length
? parseLinesRecursively(lines, index + 1, {
...result,
[key.trim()]: rest.join(":").trim(),
})
: parseLinesRecursively(lines, index + 1, result))((lines[index] || "").split(":"));
const header = parseLinesRecursively(match?.[1]?.split?.(/\r?\n/) || []);
const body = match?.[2]?.replace(/\r\n/g, "")?.startsWith("```html")
? match[2]?.match?.(/```html\r?\n([\s\S]*?)```/)?.[1]
: match?.[2];
return { ...header, html: mdToHTML(body) };
}
return data;
}
const isProduction = process.env.NODE_ENV === "production";
function getTemplateData(template) {
// dir template: dashboard, card
if (template[0][3]) {
const files = readdirSync(template[0][1]);
const data = files.map(async (el) => readFileData(path.join(template[0][1], el)));
return files.map((el, i) => [el, data[i]]);
}
// one file template: table, form
if (template.length === 1) {
const data = readFileData(template[0][1]);
return data;
}
// multi file template: select, etc
if (template.length > 1) {
const data = template.map((el) => readFileData(el[1]));
if (Array.isArray(data[0])) {
return data[0];
}
const result = {};
template.forEach((el, i) => {
Object.assign(result, typeof data[i] === "object" ? data[i] : { [el[2]]: data[i] });
});
return result;
}
return null;
}
export default function getTemplateSync(type, name) {
if (!type)
return null;
if (!name)
return null;
const key = `${type}:${name}`;
if (name === "cache" && !isProduction)
return loadTemplate; // all cache debug
// if (loadTemplate[key] && isProduction && false) return loadTemplate[key]; // from cache
// type one or multi
const templateList = Array.isArray(type)
? type
.map((el) => getTemplatePath(el))
.filter((list) => list?.filter((el) => el[0] === name).length)[0] || []
: getTemplatePath(type);
// find template
const template = templateList?.filter((el) => el[0] === name);
if (name === "list" && !isProduction)
return templateList; // all template debug
if (!template.length)
return null; // not found
loadTemplate[key] = getTemplateData(template);
return loadTemplate[key];
}