@opengis/fastify-table
Version:
core-plugins
53 lines (52 loc) • 2.79 kB
JavaScript
import Handlebars from "handlebars";
import getPGAsync from "../../plugins/pg/funcs/getPGAsync.js";
const maxLimit = 100;
/**
* Відображення даних з таблиці або запиту до БД на сторінці. За запитом отримуємо масив json із рядків бази даних.
* Є можливість застосування синтаксису sql у змінній query для формування запиту до БД.
*
* @summary Відображення контенту на сторінці. Є можливість застосування синтаксису sql у змінній query.
* @priority 5
* @type helper
* @alias contentList
* @example
* {{#contentList table="help.doc_function" query="type='api'" sql1=1 limit=1}}{{#each rows}}{{{JSON 2 this}}}{{/each}}{{/contentList}}
* @example
* {{#contentList table="help.doc_function" sql1=1 query="name like '%form%'" limit=1}}{{#each rows}}{{{JSON 2 this}}}{{/each}}{{/contentList}}
* @example
* {{#contentList table="help.article" sql=1 query="module='CORE'" limit=1}}{{#each rows}}{{{JSON 2 this}}}{{/each}}{{/contentList}}
* @param {String} table Таблиця в базі або конфіг таблиця
* @param {String} query Запит до бази
* @param {Number} limit Кількість рядків на сторінці
* @param {String} sql Вивід sql запиту
* @returns {String} Returns HTML
*/
export default async function contentList(options) {
const { table, limit, query, order, sql, debug } = options.hash;
if (!table) {
return "Table undefined";
}
try {
const pg = await getPGAsync();
const hasBrackets = table.trim().startsWith("(") && table.trim().endsWith(")");
const SQL = `select *,${pg.pk[table] || "1"}::text from ${hasBrackets ? `${table} t` : table} where ${query || "1=1"} ${order ? `order by ${order}` : ""} limit ${limit !== undefined && limit !== null ? Math.min(maxLimit, +limit) : 15}`;
const compiledSQL = Handlebars.compile(SQL)(options.data.root);
if (sql) {
return compiledSQL
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
const { rows } = await pg.query(compiledSQL);
const data = { rows, total: rows.length, ...options.data?.root };
if (debug) {
return JSON.stringify(data, null, 2);
}
return options.fn(data);
}
catch (err) {
return `Сталася помилка, зверніться до відділу підтримки.<!-- err: ${err.toString()} -->`;
}
}