@opengis/fastify-table
Version:
core-plugins
59 lines (48 loc) • 2.86 kB
JavaScript
import Handlebars from 'handlebars';
import getPG from '../../plugins/pg/funcs/getPG.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 = getPG();
const hasBrackets = table.trim().startsWith('(') && table.trim().endsWith(')');
const where = `where ${query ? query : '1=1'}`;
const _limit = limit !== undefined && limit !== null ? Math.min(maxLimit, +limit) : 15;
const _order = order ? `order by ${order}` : '';
const SQL = `select *,${pg.pk[table] || '1'}::text from ${hasBrackets ? table + ' t' : table} ${where} ${_order} limit ${_limit}`;
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()} -->`;
}
};