@opengis/fastify-table 1.3.71 → 1.3.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +86 -86
  2. package/index.js +9 -0
  3. package/package.json +1 -1
  4. package/server/helpers/format/formatAuto.js +13 -13
  5. package/server/helpers/format/formatDate.js +258 -258
  6. package/server/helpers/format/formatDigit.js +20 -20
  7. package/server/helpers/format/formatNum.js +361 -361
  8. package/server/helpers/format/formatNumber.js +54 -54
  9. package/server/helpers/format/formatRelative.js +106 -106
  10. package/server/helpers/format/formatUnit.js +38 -38
  11. package/server/helpers/format/num_format.js +41 -41
  12. package/server/helpers/funcs/_math.js +49 -49
  13. package/server/helpers/funcs/empty.js +21 -21
  14. package/server/helpers/funcs/ifCond.js +106 -106
  15. package/server/helpers/funcs/ifCondAnd.js +96 -96
  16. package/server/helpers/funcs/ifCondOr.js +98 -98
  17. package/server/helpers/funcs/inc.js +20 -20
  18. package/server/helpers/funcs/json.js +2 -2
  19. package/server/helpers/funcs/round.js +27 -27
  20. package/server/helpers/string/coalesce.js +31 -31
  21. package/server/helpers/string/concat.js +28 -28
  22. package/server/helpers/string/split.js +19 -19
  23. package/server/helpers/string/str_replace.js +60 -60
  24. package/server/helpers/string/substr.js +31 -31
  25. package/server/helpers/string/translit.js +23 -23
  26. package/server/helpers/string/utils/alphabet.js +75 -75
  27. package/server/plugins/cron/funcs/addCron.js +52 -52
  28. package/server/plugins/cron/index.js +76 -76
  29. package/server/plugins/crud/funcs/getOpt.js +14 -14
  30. package/server/plugins/crud/funcs/setOpt.js +21 -21
  31. package/server/plugins/crud/funcs/setToken.js +43 -43
  32. package/server/plugins/crud/funcs/utils/getFolder.js +11 -11
  33. package/server/plugins/crud/index.js +23 -23
  34. package/server/plugins/hook/index.js +8 -8
  35. package/server/plugins/logger/errorStatus.js +19 -19
  36. package/server/plugins/logger/index.js +26 -26
  37. package/server/plugins/migration/index.js +7 -7
  38. package/server/plugins/pg/index.js +11 -2
  39. package/server/plugins/policy/sqlInjection.js +33 -33
  40. package/server/plugins/redis/client.js +8 -8
  41. package/server/plugins/redis/funcs/redisClients.js +3 -3
  42. package/server/plugins/redis/index.js +17 -17
  43. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  44. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  45. package/server/plugins/table/funcs/getTemplates.js +19 -19
  46. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  47. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  48. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  49. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  50. package/server/plugins/table/index.js +13 -13
  51. package/server/plugins/util/index.js +7 -7
  52. package/server/routes/cron/index.js +16 -14
  53. package/server/routes/crud/index.js +8 -7
  54. package/server/routes/data/controllers/cardData.js +144 -0
  55. package/server/routes/data/controllers/cardTabData.js +58 -0
  56. package/server/routes/data/controllers/funcs/getFilterSQL/index.js +92 -0
  57. package/server/routes/data/controllers/funcs/getFilterSQL/util/formatValue.js +170 -0
  58. package/server/routes/data/controllers/funcs/getFilterSQL/util/getCustomQuery.js +13 -0
  59. package/server/routes/data/controllers/funcs/getFilterSQL/util/getFilterQuery.js +64 -0
  60. package/server/routes/data/controllers/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -0
  61. package/server/routes/data/controllers/funcs/getFilterSQL/util/getTableSql.js +34 -0
  62. package/server/routes/data/controllers/tableData.js +55 -0
  63. package/server/routes/data/controllers/tableFilter.js +16 -0
  64. package/server/routes/data/controllers/tableInfo.js +110 -0
  65. package/server/routes/data/controllers/tokenInfo.js +12 -0
  66. package/server/routes/data/controllers/utils/assignTokens.js +31 -0
  67. package/server/routes/data/controllers/utils/conditions.js +19 -0
  68. package/server/routes/data/controllers/utils/getColumns.js +9 -0
  69. package/server/routes/data/index.mjs +22 -0
  70. package/server/routes/data/schema.js +54 -0
  71. package/server/routes/dblist/index.mjs +9 -7
  72. package/server/routes/logger/controllers/logger.file.js +93 -93
  73. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  74. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  75. package/server/routes/logger/index.js +17 -17
  76. package/server/routes/menu/controllers/getMenu.js +97 -0
  77. package/server/routes/menu/controllers/interfaces.js +21 -0
  78. package/server/routes/menu/index.mjs +8 -0
  79. package/server/routes/menu/schema.js +0 -0
  80. package/server/routes/properties/controllers/properties.add.js +55 -55
  81. package/server/routes/properties/controllers/properties.get.js +17 -17
  82. package/server/routes/properties/index.js +16 -16
  83. package/server/routes/table/controllers/form.js +42 -42
  84. package/server/routes/table/controllers/search.js +74 -74
  85. package/server/routes/table/controllers/suggest.js +28 -14
  86. package/server/routes/table/index.js +10 -10
  87. package/server/routes/table/schema.js +65 -64
  88. package/server/routes/templates/controllers/getTemplate.js +51 -0
  89. package/server/routes/templates/index.mjs +10 -0
  90. package/server/routes/templates/schema.js +9 -0
  91. package/server/routes/util/controllers/status.monitor.js +8 -8
  92. package/server/routes/util/index.js +2 -2
  93. package/utils.js +2 -0
@@ -0,0 +1,97 @@
1
+ /* eslint-disable no-param-reassign */
2
+ /* eslint-disable camelcase */
3
+ /* eslint-disable no-nested-ternary */
4
+ import { join } from 'node:path';
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
6
+
7
+ import {
8
+ userTemplateDir, pgClients, applyHook, config,
9
+ } from '../../../../utils.js';
10
+
11
+ const menuCache = [];
12
+
13
+ // check module dir
14
+ const moduleDir = join(process.cwd(), 'module');
15
+ const dirs = existsSync(moduleDir)
16
+ ? readdirSync(moduleDir).map(el => join(moduleDir, el))
17
+ : [];
18
+
19
+ const isProduction = process.env.NODE_ENV === 'production';
20
+ // readMenu();
21
+
22
+ async function readMenu() {
23
+ const menuList = dirs.concat(userTemplateDir)
24
+ .map(el => join(el, 'menu.json'))
25
+ .filter(el => existsSync(el));
26
+ // const list = menuList.map(el => readFileSync(el, 'utf-8')); // sync
27
+ const list = menuList.filter((el, idx, arr) => el && arr.indexOf(el) === idx).map(el => readFileSync(el, 'utf-8')); // sync
28
+ const menus = list.reduce((p, el) => p.concat(JSON.parse(el)), [])
29
+ .map(el => ({ order: 0, ...el }))
30
+ .sort((a, b) => ((a.order > b.order) ? 1 : ((b.order > a.order) ? -1 : 0)));
31
+
32
+ if (!menuCache.length) {
33
+ menus.forEach(el => menuCache.push(el));
34
+ }
35
+
36
+ return menus;
37
+ }
38
+
39
+ export default async function adminMenu({ user = {}, session, pg = pgClients.client }, reply) {
40
+ const time = Date.now();
41
+
42
+ if (!user.uid) {
43
+ return reply.status(403).send('access restricted');
44
+ }
45
+
46
+ const menus = isProduction && menuCache.length ? menuCache : await readMenu();
47
+
48
+ const { rows } = await pgClients.client.query(`select property_key as key,property_text as val from admin.properties where property_key~'^(${config.settingKeys || 'site|map|admin'})'`);
49
+ const settings = rows.reduce((p, { key, val }) => { const [k1, k2] = key.split('.'); p[k1] = p[k1] || {}; p[k1][k2] = val; return p; }, {});
50
+
51
+ if (config.settings) Object.assign(settings, config.settings);
52
+
53
+ // update user access
54
+ const {
55
+ user_name, sur_name, father_name, email, phone, uid,
56
+ } = user;
57
+
58
+ const result = {
59
+ settings,
60
+ user: {
61
+ uid, user_name, sur_name, father_name, email, phone,
62
+ },
63
+ };
64
+ await applyHook('userMenu', result);
65
+
66
+ if (session && user?.uid && !user.user_type?.includes?.('admin') && !user.type?.includes?.('admin') && pg.pk['admin.role_access']) {
67
+ const { type, gl = [], routes = [] } = await pg.query(`select user_type as type, b.gl,routes from admin.users a
68
+ left join lateral (
69
+ select array_agg(role_id) as gl from admin.user_roles
70
+ where user_uid=a.uid
71
+ and role_id in ( select role_id from admin.roles where enabled)
72
+ )b on 1=1
73
+ left join lateral (
74
+ select array_agg(route_id) as routes from admin.role_access where role_id=any(b.gl)
75
+ )r on 1=1
76
+ where uid=$1`, [user.uid]).then(el => el.rows[0] || {});
77
+ /* const { interfaces = [] } = await pg.query(`select array_agg(route_id) as interfaces from admin.role_access
78
+ where user_uid=$1 or role_id=any($2::text[])`, [user.uid, gl]).then((res) => res.rows?.[0] || {}); */
79
+
80
+ Object.assign(user, { type, group_list: gl, routes });
81
+ session?.set?.('passport', { user });
82
+
83
+ if (type?.includes?.('admin')) {
84
+ return { time: Date.now() - time, menus, ...result };
85
+ }
86
+
87
+ const userMenus = menus.map(el => (el.menu ? { ...el, menu: el.menu.filter(item => routes?.includes(item.path)) } : el));
88
+ const filtered = userMenus.filter(el => el.menu?.length || routes?.includes(el.path));
89
+ return { time: Date.now() - time, menus: filtered, ...result };
90
+ // .filter((el, idx, arr) => arr.map((el) => el?.ua || el?.en || el?.name).indexOf(el?.ua || el?.en || el?.name) === idx)
91
+ }
92
+
93
+ // skip dupes?
94
+ // .filter((el, idx, arr) => arr.map((el) => el?.ua || el?.en || el?.name).indexOf(el?.ua || el?.en || el?.name) === idx)
95
+
96
+ return { time: Date.now() - time, menus, ...result };
97
+ }
@@ -0,0 +1,21 @@
1
+ import { pgClients, getTemplatePath } from '../../../../utils.js';
2
+
3
+ export default async function getInterfaces({ pg = pgClients.client }) {
4
+ const { rows = [] } = await pg.query('select route_id, alias, table_name, title, enabled from admin.routes');
5
+
6
+ const interfaces = rows
7
+ .filter((el, idx, arr) => el.table_name && arr.findIndex(item => item.route_id === el.route_id) === idx)
8
+ .filter(el => pg.pk?.[el.table_name || ''])
9
+ .filter(el => !['log.', 'admin.', 'setting.'].find(item => el.table_name.startsWith(item)))
10
+ .map(el => ({
11
+ title: el.title,
12
+ alias: el.alias,
13
+ table: el.table_name,
14
+ route: el.route_id,
15
+ enabled: el.enabled,
16
+ }));
17
+
18
+ const all = getTemplatePath('table').map(el => el[0]);
19
+
20
+ return interfaces.filter(el => el.alias && all.includes(el.alias));
21
+ }
@@ -0,0 +1,8 @@
1
+ import getMenu from './controllers/getMenu.js';
2
+ import interfaces from './controllers/interfaces.js';
3
+
4
+ export default async function route(app, config = {}) {
5
+ const { prefix = '/api' } = config;
6
+ app.get(`${prefix}/user-menu`, getMenu);
7
+ app.get(`${prefix}/interfaces`, { config: { policy: ['admin'] } }, interfaces);
8
+ }
File without changes
@@ -1,55 +1,55 @@
1
- import { dataInsert } from '../../../../utils.js';
2
-
3
- const table = 'crm.properties';
4
-
5
- function checkKeyType({ body, key }) {
6
- if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
- return { [key]: 'int' };
8
- } if (typeof body[key] === 'object') {
9
- return { [key]: 'json' };
10
- }
11
- if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
- return { [key]: 'date' };
13
- }
14
- return { [key]: 'text' };
15
- }
16
-
17
- export default async function addExtraProperties({
18
- pg, params = {}, body = {}, user = {},
19
- }) {
20
- const { id } = params;
21
- const { uid } = user;
22
- if (!uid) {
23
- return { message: 'access restricted: uid', status: 403 };
24
- }
25
- if (!id) {
26
- return { message: 'not enougn params: 1', status: 400 };
27
- }
28
- const extraProperties = Object.keys(body);
29
- if (!extraProperties.length) {
30
- return { message: 'not enougn params: 2', status: 400 };
31
- }
32
-
33
- if (!pg.pk?.[table]) {
34
- return { message: 'table not found: crm.properties', status: 400 };
35
- }
36
-
37
- await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
38
- const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
39
- const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
40
- const propertyType = keyTypeMatch[key];
41
- const { rows = [] } = await dataInsert({
42
- pg,
43
- table,
44
- data: {
45
- property_type: propertyType,
46
- property_key: key,
47
- object_id: id,
48
- [`property_${propertyType}`]: body[key],
49
- },
50
- uid,
51
- });
52
- return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
53
- }));
54
- return { message: { rows: res }, status: 200 };
55
- }
1
+ import { dataInsert } from '../../../../utils.js';
2
+
3
+ const table = 'crm.properties';
4
+
5
+ function checkKeyType({ body, key }) {
6
+ if (typeof body[key] === 'number' && (!/\D/.test(body[key].toString()) && body[key].toString().length < 10)) {
7
+ return { [key]: 'int' };
8
+ } if (typeof body[key] === 'object') {
9
+ return { [key]: 'json' };
10
+ }
11
+ if (Date.parse(body[key], 'yyyy/MM/ddTHH:mm:ss.000Z')) {
12
+ return { [key]: 'date' };
13
+ }
14
+ return { [key]: 'text' };
15
+ }
16
+
17
+ export default async function addExtraProperties({
18
+ pg, params = {}, body = {}, user = {},
19
+ }) {
20
+ const { id } = params;
21
+ const { uid } = user;
22
+ if (!uid) {
23
+ return { message: 'access restricted: uid', status: 403 };
24
+ }
25
+ if (!id) {
26
+ return { message: 'not enougn params: 1', status: 400 };
27
+ }
28
+ const extraProperties = Object.keys(body);
29
+ if (!extraProperties.length) {
30
+ return { message: 'not enougn params: 2', status: 400 };
31
+ }
32
+
33
+ if (!pg.pk?.[table]) {
34
+ return { message: 'table not found: crm.properties', status: 400 };
35
+ }
36
+
37
+ await pg.query('delete from crm.properties where object_id=$1', [id]); // rewrite?
38
+ const keyTypeMatch = extraProperties.filter((key) => body[key]).reduce((acc, curr) => Object.assign(acc, checkKeyType({ body, key: curr })), {});
39
+ const res = await Promise.all(Object.keys(keyTypeMatch).map(async (key) => {
40
+ const propertyType = keyTypeMatch[key];
41
+ const { rows = [] } = await dataInsert({
42
+ pg,
43
+ table,
44
+ data: {
45
+ property_type: propertyType,
46
+ property_key: key,
47
+ object_id: id,
48
+ [`property_${propertyType}`]: body[key],
49
+ },
50
+ uid,
51
+ });
52
+ return { id: rows[0]?.property_id, type: propertyType, value: body[key] };
53
+ }));
54
+ return { message: { rows: res }, status: 200 };
55
+ }
@@ -1,17 +1,17 @@
1
- export default async function getExtraProperties({
2
- pg, params = {},
3
- }) {
4
- const { id } = params;
5
- if (!id) {
6
- return { message: 'not enougn params', status: 400 };
7
- }
8
-
9
- const { rows = [] } = pg.pk?.['crm.properties']
10
- ? await pg.query(`select property_key, property_type, property_text, property_int,
11
- property_json, property_date from crm.properties where property_key is not null and object_id=$1`, [id])
12
- : {};
13
- if (!rows.length) return {};
14
-
15
- const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.property_key]: curr[`property_${curr.property_type}`] }), {});
16
- return { message: data, status: 200 };
17
- }
1
+ export default async function getExtraProperties({
2
+ pg, params = {},
3
+ }) {
4
+ const { id } = params;
5
+ if (!id) {
6
+ return { message: 'not enougn params', status: 400 };
7
+ }
8
+
9
+ const { rows = [] } = pg.pk?.['crm.properties']
10
+ ? await pg.query(`select property_key, property_type, property_text, property_int,
11
+ property_json, property_date from crm.properties where property_key is not null and object_id=$1`, [id])
12
+ : {};
13
+ if (!rows.length) return {};
14
+
15
+ const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.property_key]: curr[`property_${curr.property_type}`] }), {});
16
+ return { message: data, status: 200 };
17
+ }
@@ -1,16 +1,16 @@
1
- import getExtraProperties from './controllers/properties.get.js';
2
- import addExtraProperties from './controllers/properties.add.js';
3
-
4
- const propertiesSchema = {
5
- params: {
6
- id: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
- },
8
- };
9
-
10
- async function plugin(fastify, config = {}) {
11
- const prefix = config.prefix || '/api';
12
- fastify.get(`${prefix}/properties/:id`, { schema: propertiesSchema }, getExtraProperties);
13
- fastify.post(`${prefix}/properties/:id`, { schema: propertiesSchema }, addExtraProperties);
14
- }
15
-
16
- export default plugin;
1
+ import getExtraProperties from './controllers/properties.get.js';
2
+ import addExtraProperties from './controllers/properties.add.js';
3
+
4
+ const propertiesSchema = {
5
+ params: {
6
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
7
+ },
8
+ };
9
+
10
+ async function plugin(app, config = {}) {
11
+ const { prefix = '/api' } = config;
12
+ app.get(`${prefix}/properties/:id`, { schema: propertiesSchema }, getExtraProperties);
13
+ app.post(`${prefix}/properties/:id`, { schema: propertiesSchema }, addExtraProperties);
14
+ }
15
+
16
+ export default plugin;
@@ -1,42 +1,42 @@
1
- import { applyHook, getTemplate } from '../../../../utils.js';
2
-
3
- const sql = `select property_key as key, property_json as json, property_int as int,
4
- property_text as text from admin.properties where 1=1`;
5
-
6
- async function getSettings({ pg }) {
7
- const { rows = [] } = await pg.query(sql);
8
- const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
- return data;
10
- }
11
-
12
- export default async function formFunction(req) {
13
- const time = Date.now();
14
-
15
- const { pg, params, user } = req;
16
- const hookData = await applyHook('preForm', { form: params?.form, user });
17
-
18
- if (hookData?.message && hookData?.status) {
19
- return { message: hookData?.message, status: hookData?.status };
20
- }
21
-
22
- const form = await getTemplate('form', hookData?.form || params?.form);
23
- if (!form) { return { status: 404, message: 'not found' }; }
24
-
25
- // replace settings
26
- const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
- if (arr?.length) {
28
- const string = JSON.stringify(form);
29
- const settings = await getSettings({ pg });
30
- const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
- const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
- return { time: Date.now() - time, form: JSON.parse(res) };
33
- }
34
-
35
- const res = { time: Date.now() - time, form };
36
- const res1 = await applyHook('afterForm', {
37
- form: hookData?.form || params?.form,
38
- payload: res,
39
- user,
40
- });
41
- return res1 || { time: Date.now() - time, form };
42
- }
1
+ import { applyHook, getTemplate } from '../../../../utils.js';
2
+
3
+ const sql = `select property_key as key, property_json as json, property_int as int,
4
+ property_text as text from admin.properties where 1=1`;
5
+
6
+ async function getSettings({ pg }) {
7
+ const { rows = [] } = await pg.query(sql);
8
+ const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
+ return data;
10
+ }
11
+
12
+ export default async function formFunction(req) {
13
+ const time = Date.now();
14
+
15
+ const { pg, params, user } = req;
16
+ const hookData = await applyHook('preForm', { form: params?.form, user });
17
+
18
+ if (hookData?.message && hookData?.status) {
19
+ return { message: hookData?.message, status: hookData?.status };
20
+ }
21
+
22
+ const form = await getTemplate('form', hookData?.form || params?.form);
23
+ if (!form) { return { status: 404, message: 'not found' }; }
24
+
25
+ // replace settings
26
+ const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
+ if (arr?.length) {
28
+ const string = JSON.stringify(form);
29
+ const settings = await getSettings({ pg });
30
+ const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
+ const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
+ return { time: Date.now() - time, form: JSON.parse(res) };
33
+ }
34
+
35
+ const res = { time: Date.now() - time, form };
36
+ const res1 = await applyHook('afterForm', {
37
+ form: hookData?.form || params?.form,
38
+ payload: res,
39
+ user,
40
+ });
41
+ return res1 || { time: Date.now() - time, form };
42
+ }
@@ -1,74 +1,74 @@
1
- import {
2
- getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
- } from '../../../../utils.js';
4
-
5
- function sequence(tables, data, fn) {
6
- return tables.reduce((promise, table) => promise.then(() => fn({
7
- ...data, tableName: table.replace('.json', ''),
8
- })), Promise.resolve());
9
- }
10
-
11
- async function getData({
12
- pg, tableName, query = {}, maxLimit, res,
13
- }) {
14
- const loadTable = await getTemplate('table', tableName);
15
-
16
- if (!loadTable) { return { message: 'not found', status: 404 }; }
17
-
18
- const {
19
- table, columns, meta,
20
- } = loadTable;
21
-
22
- const { pk } = await getMeta(table);
23
-
24
- const cols = columns.map((el) => el.name || el).join(',');
25
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
- const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
-
28
- const limit = Math.max(maxLimit - res.rows.length, 0);
29
- // Math.max(query.offset - res.rows.length,0)
30
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
-
32
- const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
-
34
- const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
- const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
- if (query.sql) {
37
- res.sql.push(q);
38
- return null;
39
- }
40
-
41
- const { rows } = await pg.query(q);
42
-
43
- const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
-
45
- await metaFormat({ rows, table: tableName });
46
- res.total += +total;
47
- rows.forEach((row) => {
48
- const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
- res.rows.push({
50
- ...row, register: tableName, register_title: loadTable.ua, href,
51
- });
52
- });
53
- return null;
54
- }
55
-
56
- export default async function search({
57
- pg, funcs, query = {},
58
- }) {
59
- const time = Date.now();
60
-
61
- const tables = query.table ? [query.table] : await getTemplates('table');
62
- const res = { rows: [], sql: [], total: 0 };
63
-
64
- const maxLimit = Math.min(100, query.limit || '16');
65
- await sequence(tables, {
66
- pg, funcs, query, maxLimit, res,
67
- }, getData);
68
-
69
- if (query.sql) return res.sql.join(';\n');
70
-
71
- return {
72
- time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
- };
74
- }
1
+ import {
2
+ getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
+ } from '../../../../utils.js';
4
+
5
+ function sequence(tables, data, fn) {
6
+ return tables.reduce((promise, table) => promise.then(() => fn({
7
+ ...data, tableName: table.replace('.json', ''),
8
+ })), Promise.resolve());
9
+ }
10
+
11
+ async function getData({
12
+ pg, tableName, query = {}, maxLimit, res,
13
+ }) {
14
+ const loadTable = await getTemplate('table', tableName);
15
+
16
+ if (!loadTable) { return { message: 'not found', status: 404 }; }
17
+
18
+ const {
19
+ table, columns, meta,
20
+ } = loadTable;
21
+
22
+ const { pk } = await getMeta(table);
23
+
24
+ const cols = columns.map((el) => el.name || el).join(',');
25
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
+ const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
+
28
+ const limit = Math.max(maxLimit - res.rows.length, 0);
29
+ // Math.max(query.offset - res.rows.length,0)
30
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
+
32
+ const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
+
34
+ const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
+ const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
+ if (query.sql) {
37
+ res.sql.push(q);
38
+ return null;
39
+ }
40
+
41
+ const { rows } = await pg.query(q);
42
+
43
+ const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
+
45
+ await metaFormat({ rows, table: tableName });
46
+ res.total += +total;
47
+ rows.forEach((row) => {
48
+ const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
+ res.rows.push({
50
+ ...row, register: tableName, register_title: loadTable.ua, href,
51
+ });
52
+ });
53
+ return null;
54
+ }
55
+
56
+ export default async function search({
57
+ pg, funcs, query = {},
58
+ }) {
59
+ const time = Date.now();
60
+
61
+ const tables = query.table ? [query.table] : await getTemplates('table');
62
+ const res = { rows: [], sql: [], total: 0 };
63
+
64
+ const maxLimit = Math.min(100, query.limit || '16');
65
+ await sequence(tables, {
66
+ pg, funcs, query, maxLimit, res,
67
+ }, getData);
68
+
69
+ if (query.sql) return res.sql.join(';\n');
70
+
71
+ return {
72
+ time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
+ };
74
+ }
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
 
4
4
  import {
5
- config, getPG, getTemplate, getSelectMeta, getMeta, applyHook, getSelectVal, logger,
5
+ config, getPG, getTemplate, getSelectMeta, getMeta, applyHook, getSelectVal, logger, getSelect,
6
6
  } from '../../../../utils.js';
7
7
 
8
8
  const limit = 50;
@@ -12,12 +12,19 @@ const headers = {
12
12
  'Cache-Control': 'no-cache',
13
13
  };
14
14
 
15
- function getTableColumnMeta(table, column, filtered) {
15
+ async function getTableColumnMeta(tableName, column, filtered, pg) {
16
+ if (!tableName || !column) { return null; }
17
+
18
+ const loadTable = await getTemplate('table', tableName);
19
+ const { data: clsName } = loadTable?.columns?.find?.(el => el.name === column) || {};
20
+ const { arr } = await getSelect(clsName, pg) || {};
21
+
16
22
  const original = {
17
- true: `with c(id,text) as (select ${column}, ${column} from ${table} group by ${column}) select id, text from c`,
18
- false: `with c(id,text) as (select ${column}, ${column}, count(*) from ${table} group by ${column} limit ${limit}) select * from c`,
23
+ true: `with c(id,text) as (select ${column} as id, ${column} as text from ${loadTable?.table || tableName} group by ${column}) select id, text from c`,
24
+ false: `with c(id,text) as (select ${column} as id, ${column} as text, count(*) from ${loadTable?.table || tableName} group by ${column} limit ${limit}) select * from c`,
19
25
  }[!!filtered];
20
26
  return {
27
+ arr,
21
28
  original,
22
29
  searchQuery: '(lower("text") ~ $1 )',
23
30
  pk: 'id',
@@ -41,13 +48,13 @@ export default async function suggest(req) {
41
48
  }
42
49
  }
43
50
 
44
- const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
51
+ const [table, column] = params.data?.includes(':') ? params.data.split(':') : [query.token, query.column];
45
52
  const selectName = query.sel || query.name || params.data;
46
53
 
47
54
  if (!selectName) return { status: 400, message: 'name is required' };
48
55
 
49
56
  const { body: hookBody } = table || query.token ? await applyHook('preSuggest', { pg: pg1, table: table || query.token }) || {} : {};
50
- const body = await getTemplate('table', table);
57
+ const body = await getTemplate('table', table || query.token);
51
58
  const tableName = hookBody?.table || body?.table || table || query.token;
52
59
 
53
60
  if (table && !pg1.pk?.[tableName]) {
@@ -55,7 +62,7 @@ export default async function suggest(req) {
55
62
  }
56
63
 
57
64
  const tableMeta = await getMeta({ pg: pg1, table: tableName });
58
- const columnExists = (hookBody?.columns || body?.columns || tableMeta?.columns)?.find((col) => col?.name === column);
65
+ const columnExists = (hookBody?.columns || body?.columns || tableMeta?.columns)?.find(col => col?.name === (column || query.column));
59
66
 
60
67
  if (table && (!column || !columnExists)) {
61
68
  return { status: 400, message: 'param name is invalid: 2' };
@@ -65,8 +72,8 @@ export default async function suggest(req) {
65
72
  return { status: 400, message: 'param limit is invalid' };
66
73
  }
67
74
 
68
- const meta = table && column
69
- ? getTableColumnMeta(table, column, query?.key || query?.val)
75
+ const meta = tableName && column
76
+ ? await getTableColumnMeta(table, column, query?.key || query?.val, pg1)
70
77
  : await getSelectMeta({
71
78
  pg: pg1, name: selectName, nocache: query?.nocache, parent,
72
79
  });
@@ -95,17 +102,19 @@ export default async function suggest(req) {
95
102
  const column1 = columns.find(el => el.name === query.column);
96
103
  const args = { table: tableName };
97
104
  if (!column1) return [];
98
- const sqlCls = `select array_agg(distinct value)::text[] from (select ${pg.pgType?.[column1.dataTypeID]?.includes('[]') ? `unnest(${column1.name})` : `${column1.name}`} as value from ${(loadTable?.table || tableName).replace(/'/g, "''")} where ${hookBody?.query || loadTable?.query || '1=1'})q`;
105
+ const sqlCls = query.count
106
+ ? `select value, count(*) from (select ${pg.pgType?.[column1.dataTypeID]?.includes('[]') ? `unnest(${column1.name})` : `${column1.name}`} as value from ${(loadTable?.table || tableName).replace(/'/g, "''")} where ${hookBody?.query || loadTable?.query || '1=1'})q group by value`
107
+ : `select array_agg(distinct value)::text[] from (select ${pg.pgType?.[column1.dataTypeID]?.includes('[]') ? `unnest(${column1.name})` : `${column1.name}`} as value from ${(loadTable?.table || tableName).replace(/'/g, "''")} where ${hookBody?.query || loadTable?.query || '1=1'})q`;
99
108
 
100
109
  if (query.sql && (config.local || user?.user_type?.includes?.('admin'))) {
101
110
  return sqlCls;
102
111
  }
103
112
 
104
- if (pg.pk?.[loadTable?.table || tableName] && column?.name) {
105
- const vals = await pg.queryCache(sqlCls, args).then(el => el.rows?.[0]?.array_agg || []);
106
- // console.log(vals);
113
+ if (pg.pk?.[loadTable?.table || tableName] && column1?.name) {
114
+ const qRes = await pg.queryCache(sqlCls, args);
115
+ const vals = (query.count ? qRes.rows?.map?.(el => el.value?.toString?.()) : qRes.rows?.[0]?.array_agg) || [];
107
116
 
108
- const lower = query.key?.toLowerCase();
117
+ const lower = query.key?.toLowerCase?.();
109
118
  const data1 = query.key || query.val
110
119
  ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
111
120
  : arr;
@@ -113,6 +122,11 @@ export default async function suggest(req) {
113
122
  const data2 = data1.filter((el) => el.id && vals.includes(el.id.toString()));
114
123
  const data = data2.slice(0, Math.min(query.limit || limit, limit));
115
124
 
125
+ if (data.length && query.count) {
126
+ const counts = qRes.rows?.reduce?.((acc, curr) => ({ ...acc, [curr.value]: curr.count }), {});
127
+ data.forEach(el => Object.assign(el, { count: counts?.[el.id] || 0 }));
128
+ }
129
+
116
130
  if (config.debug) {
117
131
  logger.file('suggest/debug', {
118
132
  type: 1,