@opengis/fastify-table
Version:
core-plugins
81 lines (80 loc) • 3.42 kB
JavaScript
import { handlebars } from "../../../../helpers/index.js";
import getTemplate from "../getTemplate.js";
import getTemplates from "../getTemplates.js";
import getSelectVal from "./getSelectVal.js";
import pgClients from "../../../pg/pgClients.js";
export default async function metaFormat({ rows: original, table, cls = {}, htmls = {}, sufix = true, reassign = true, }, pg = pgClients.client) {
const loadTable = table ? await getTemplate("table", table) : {};
const selectCols = Object.keys(cls || {})
.map((key) => ({ name: key, data: cls[key] }))
.concat(loadTable?.columns?.filter((e) => e.data) || []);
const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({
name: el,
data: loadTable?.meta?.cls[el],
}));
const actualClsObj = selectCols
.concat(metaCls)
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.data }), {});
const list = getTemplates(["cls", "select"]).map((el) => el[0]);
const columnNameAsCls = Object.keys(original?.[0] || {})
.filter((key) => !actualClsObj[key] &&
(list.includes(`${table}.${key}`) || list.includes(key)))
.map((key) => ({
name: key,
data: list.find((clsName) => [key, `${table}.${key}`].includes(clsName)),
}));
const htmlCols = Object.keys(htmls || {})
.map((key) => ({ name: key, html: htmls[key] }))
.concat(loadTable?.columns?.filter?.((e) => e.name && e.html && e.format && ["html", "slot"].includes(e.format)) || []);
if (!original?.length ||
(!selectCols?.length &&
!metaCls?.length &&
!columnNameAsCls.length &&
!htmlCols?.length))
return original;
const rows = reassign ? original : JSON.parse(JSON.stringify(original));
// html && slot (vue component) format
await Promise.all(htmlCols.map(async (attr) => {
await Promise.all(rows.filter(Boolean).map(async (row) => {
const html = await handlebars.compile(attr.html)(row);
Object.assign(row, {
[attr.name]: html
?.replaceAll?.(/<[^>]*>/g, "")
?.replace?.(/\n/g, "")
?.trim?.(),
});
}));
}));
// cls & select format
await Promise.all(selectCols
.concat(metaCls)
.concat(columnNameAsCls)
?.map(async (attr) => {
const values = [
...new Set(rows?.map((el) => el[attr.name]).flat()),
].filter((el) => (typeof el === "boolean" ? true : el));
if (!values.length)
return null;
const clsValues = await getSelectVal({ pg, name: attr.data, values });
if (!clsValues)
return null;
rows.forEach((el) => {
const val = el[attr.name]?.map?.((c) => c ? clsValues[c.toString()] || clsValues[c] || c : null) ||
clsValues[el[attr.name]?.toString()] ||
clsValues[el[attr.name]] ||
el[attr.name];
if (!val)
return;
if (!sufix) {
Object.assign(el, { [attr.name]: val.text || val });
}
else {
Object.assign(el, {
[val?.color ? `${attr.name}_data` : `${attr.name}_text`]: val.color ? val : val.text || val,
});
}
});
return null;
}));
return rows;
}