@opengis/fastify-table 1.0.82 → 1.0.84

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 (65) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +253 -245
  3. package/README.md +26 -26
  4. package/config.js +10 -10
  5. package/cron/controllers/cronApi.js +22 -22
  6. package/cron/controllers/utils/cronList.js +1 -1
  7. package/cron/funcs/addCron.js +131 -131
  8. package/cron/index.js +10 -10
  9. package/crud/controllers/utils/checkXSS.js +45 -45
  10. package/crud/controllers/utils/xssInjection.js +72 -72
  11. package/crud/funcs/dataDelete.js +15 -15
  12. package/crud/funcs/dataUpdate.js +24 -24
  13. package/crud/funcs/getToken.js +27 -27
  14. package/crud/funcs/isFileExists.js +13 -13
  15. package/crud/funcs/setToken.js +53 -53
  16. package/crud/index.js +36 -36
  17. package/index.js +1 -1
  18. package/migration/exec.migrations.js +75 -75
  19. package/notification/controllers/testEmail.js +49 -49
  20. package/notification/funcs/sendNotification.js +111 -111
  21. package/notification/funcs/utils/sendEmail.js +39 -39
  22. package/notification/index.js +38 -38
  23. package/package.json +26 -26
  24. package/pg/funcs/getPG.js +30 -30
  25. package/redis/funcs/getRedis.js +23 -23
  26. package/server/migrations/0.sql +14 -0
  27. package/server/migrations/crm.sql +150 -150
  28. package/server/migrations/log.sql +43 -43
  29. package/server/templates/select/test.storage.data.json +3 -3
  30. package/server/templates/select/test.suggest.ato_new.json +2 -2
  31. package/server/templates/select/test.suggest.ato_new.sql +25 -25
  32. package/server/templates/select/test.suggest.data.json +4 -4
  33. package/server/templates/select/test.suggest.parent.sql +2 -2
  34. package/server.js +14 -14
  35. package/table/controllers/card.js +44 -44
  36. package/table/controllers/data.js +97 -97
  37. package/table/controllers/filter.js +37 -37
  38. package/table/controllers/form.js +28 -28
  39. package/table/controllers/search.js +72 -72
  40. package/table/controllers/suggest.js +18 -1
  41. package/table/controllers/utils/getSelect.js +20 -20
  42. package/table/controllers/utils/getSelectMeta.js +66 -66
  43. package/table/controllers/utils/getTemplate.js +28 -28
  44. package/table/controllers/utils/getTemplates.js +18 -18
  45. package/table/funcs/metaFormat/index.js +27 -27
  46. package/table/index.js +80 -78
  47. package/test/api/crud.xss.test.js +72 -72
  48. package/test/api/notification.test.js +37 -37
  49. package/test/api/suggest.test.js +65 -65
  50. package/test/api/table.test.js +57 -57
  51. package/test/api/widget.test.js +114 -114
  52. package/test/config.example +18 -18
  53. package/test/funcs/crud.test.js +76 -76
  54. package/test/funcs/notification.test.js +31 -31
  55. package/test/funcs/pg.test.js +34 -34
  56. package/test/funcs/redis.test.js +19 -19
  57. package/test/templates/cls/test.json +9 -9
  58. package/test/templates/form/cp_building.form.json +32 -32
  59. package/test/templates/select/account_id.json +3 -3
  60. package/test/templates/select/storage.data.json +2 -2
  61. package/test/templates/table/gis.dataset.table.json +20 -20
  62. package/util/controllers/next.id.js +4 -4
  63. package/util/controllers/properties.add.js +50 -50
  64. package/util/controllers/properties.get.js +19 -19
  65. package/widget/index.js +40 -40
@@ -1,97 +1,97 @@
1
- import getTemplate from './utils/getTemplate.js';
2
- import getFilterSQL from '../funcs/getFilterSQL/index.js';
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
- import metaFormat from '../funcs/metaFormat/index.js';
5
- import getAccess from '../../crud/funcs/getAccess.js';
6
- import setToken from '../../crud/funcs/setToken.js';
7
- import gisIRColumn from './utils/gisIRColumn.js';
8
-
9
- const maxLimit = 100;
10
- export default async function dataAPI({
11
- pg, params, funcs = {}, query = {}, opt = {}, uid: uid1, req, session,
12
- }) {
13
- const time = Date.now();
14
-
15
- const uid = session?.passport?.user?.uid || uid1 || query.uid || 0;
16
-
17
- const loadTable = await getTemplate('table', params.table);
18
-
19
- if (!loadTable) { return { message: 'template not found', status: 404 }; }
20
-
21
- const {
22
- table, columns, sql, cardSql, filters, form, meta, sqlColumns, ispublic,
23
- } = loadTable;
24
- const { pk, columns: dbColumns = [] } = await getMeta(table);
25
-
26
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
27
-
28
- const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
29
- const columnList = dbColumns.map((el) => el.name || el).join(',');
30
- const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
31
- const cardSqlFiltered = opt?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
32
- const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (select json_agg(row_to_json(q)) as ${el.name} from (${el.sql})q) ct${i} on 1=1 `).join('') || '' : '';
33
-
34
- if (params.id && columnList.includes(params.id)) {
35
- return gisIRColumn({
36
- pg, funcs, layer: params.table, column: params.id, sql: query.sql,
37
- });
38
- }
39
-
40
- const fData = query.filter || query.search ? await getFilterSQL({
41
- filter: query.filter,
42
- search: query.search,
43
- table: params.table,
44
- json: 1,
45
- }) : {};
46
-
47
- const keyQuery = query.key && loadTable.key && !(opt?.id || params.id) ? `${loadTable.key}=$1` : null;
48
-
49
- const limit = Math.min(maxLimit, +(query.limit || 20));
50
-
51
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
52
- // id, query, filter
53
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
54
-
55
- const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
56
- const state = loadTable.filterState && query.state ? loadTable.filterState[query.state]?.sql : null;
57
- const custom = loadTable.filterCustom && query.custom ? loadTable.filterCustom[query.custom]?.sql : null;
58
- const search = loadTable.meta?.search && query.search ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search}%'`).join(' or ')})` : null;
59
-
60
- const access = await getAccess(req, params.table);
61
- const where = [(opt?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, state, custom, search, access?.query || '1=1'].filter((el) => el);
62
- const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
63
- const q = `select ${pk ? `"${pk}" as id,` : ''} ${columnList.includes('geom') ? 'st_asgeojson(geom)::json as geom,' : ''} ${query.id || query.key ? '*' : sqlColumns || cols || '*'} ${cardColumns} from ${table} t ${sqlTable} ${cardSqlTable} where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
64
-
65
- if (query.sql === '1') { return q; }
66
-
67
- const { rows } = await pg.query(q, (opt?.id || params.id ? [opt?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
68
-
69
- const total = keyQuery || opt?.id || params.id ? rows.length : await pg.queryCache(`select count(*) from ${table} t ${sqlTable} where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
70
-
71
- await metaFormat({ rows, table: params.table });
72
- const res = {
73
- time: Date.now() - time, card: loadTable.card, actions: loadTable.actions, access, total, count: rows.length, pk, form, rows, meta, columns, filters,
74
- };
75
-
76
- if (!funcs.config?.security?.disableToken) {
77
- const addTokens = setToken({
78
- ids: [JSON.stringify({ add: loadTable.table, form: loadTable.form })],
79
- mode: 'a',
80
- uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
81
- array: 1,
82
- });
83
- Object.assign(res, { addToken: addTokens[0] });
84
-
85
- rows.forEach((row) => {
86
- const editTokens = setToken({
87
- ids: [JSON.stringify({ id: row.id, table: loadTable.table, form: loadTable.form })],
88
- mode: 'w',
89
- uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
90
- array: 1,
91
- });
92
- Object.assign(row, { token: editTokens[0] });
93
- });
94
- }
95
-
96
- return res;
97
- }
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getFilterSQL from '../funcs/getFilterSQL/index.js';
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+ import metaFormat from '../funcs/metaFormat/index.js';
5
+ import getAccess from '../../crud/funcs/getAccess.js';
6
+ import setToken from '../../crud/funcs/setToken.js';
7
+ import gisIRColumn from './utils/gisIRColumn.js';
8
+
9
+ const maxLimit = 100;
10
+ export default async function dataAPI({
11
+ pg, params, funcs = {}, query = {}, opt = {}, uid: uid1, req, session,
12
+ }) {
13
+ const time = Date.now();
14
+
15
+ const uid = session?.passport?.user?.uid || uid1 || query.uid || 0;
16
+
17
+ const loadTable = await getTemplate('table', params.table);
18
+
19
+ if (!loadTable) { return { message: 'template not found', status: 404 }; }
20
+
21
+ const {
22
+ table, columns, sql, cardSql, filters, form, meta, sqlColumns, ispublic,
23
+ } = loadTable;
24
+ const { pk, columns: dbColumns = [] } = await getMeta(table);
25
+
26
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
27
+
28
+ const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
29
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
30
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
31
+ const cardSqlFiltered = opt?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
32
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (select json_agg(row_to_json(q)) as ${el.name} from (${el.sql})q) ct${i} on 1=1 `).join('') || '' : '';
33
+
34
+ if (params.id && columnList.includes(params.id)) {
35
+ return gisIRColumn({
36
+ pg, funcs, layer: params.table, column: params.id, sql: query.sql,
37
+ });
38
+ }
39
+
40
+ const fData = query.filter || query.search ? await getFilterSQL({
41
+ filter: query.filter,
42
+ search: query.search,
43
+ table: params.table,
44
+ json: 1,
45
+ }) : {};
46
+
47
+ const keyQuery = query.key && loadTable.key && !(opt?.id || params.id) ? `${loadTable.key}=$1` : null;
48
+
49
+ const limit = Math.min(maxLimit, +(query.limit || 20));
50
+
51
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
52
+ // id, query, filter
53
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
54
+
55
+ const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
56
+ const state = loadTable.filterState && query.state ? loadTable.filterState[query.state]?.sql : null;
57
+ const custom = loadTable.filterCustom && query.custom ? loadTable.filterCustom[query.custom]?.sql : null;
58
+ const search = loadTable.meta?.search && query.search ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search}%'`).join(' or ')})` : null;
59
+
60
+ const access = await getAccess(req, params.table);
61
+ const where = [(opt?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, state, custom, search, access?.query || '1=1'].filter((el) => el);
62
+ const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
63
+ const q = `select ${pk ? `"${pk}" as id,` : ''} ${columnList.includes('geom') ? 'st_asgeojson(geom)::json as geom,' : ''} ${query.id || query.key ? '*' : sqlColumns || cols || '*'} ${cardColumns} from ${table} t ${sqlTable} ${cardSqlTable} where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
64
+
65
+ if (query.sql === '1') { return q; }
66
+
67
+ const { rows } = await pg.query(q, (opt?.id || params.id ? [opt?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
68
+
69
+ const total = keyQuery || opt?.id || params.id ? rows.length : await pg.queryCache(`select count(*) from ${table} t ${sqlTable} where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
70
+
71
+ await metaFormat({ rows, table: params.table });
72
+ const res = {
73
+ time: Date.now() - time, card: loadTable.card, actions: loadTable.actions, access, total, count: rows.length, pk, form, rows, meta, columns, filters,
74
+ };
75
+
76
+ if (!funcs.config?.security?.disableToken) {
77
+ const addTokens = setToken({
78
+ ids: [JSON.stringify({ add: loadTable.table, form: loadTable.form })],
79
+ mode: 'a',
80
+ uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
81
+ array: 1,
82
+ });
83
+ Object.assign(res, { addToken: addTokens[0] });
84
+
85
+ rows.forEach((row) => {
86
+ const editTokens = setToken({
87
+ ids: [JSON.stringify({ id: row.id, table: loadTable.table, form: loadTable.form })],
88
+ mode: 'w',
89
+ uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
90
+ array: 1,
91
+ });
92
+ Object.assign(row, { token: editTokens[0] });
93
+ });
94
+ }
95
+
96
+ return res;
97
+ }
@@ -1,37 +1,37 @@
1
- import getTemplate from './utils/getTemplate.js';
2
- import getSelect from './utils/getSelect.js';
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
-
5
- export default async function filter(req) {
6
- const time = Date.now();
7
-
8
- const {
9
- params,
10
- } = req;
11
- const loadTable = await getTemplate('table', params.table);
12
- if (!loadTable) { return { status: 404, message: 'not found' }; }
13
- const { columns } = await getMeta({ table: loadTable.table });
14
-
15
- const filters = loadTable?.filters || loadTable?.filterList || [];
16
- await Promise.all(filters.filter((el) => el.data).map(async (el) => {
17
- const cls = await getSelect(el.data);
18
- if (!cls?.arr || !loadTable.table) return;
19
- const { dataTypeID } = columns.find((item) => item.name === el.id) || {};
20
- const countArr = req.pg.pgType[dataTypeID]?.includes('[]')
21
- ? await req.pg.queryCache(`select unnest(${el.id})::text as id,count(*) from ${loadTable.table} group by unnest(${el.id})`)
22
- : await req.pg.queryCache(`select ${el.id}::text as id,count(*) from ${loadTable.table} group by ${el.id}`);
23
-
24
- const options = countArr.rows.map(cel => {
25
- const data = cls?.arr.find(c => c.id === cel.id);
26
- return { ...cel, ...data };
27
- });
28
- Object.assign(el, { options });
29
- }));
30
- return {
31
- time: Date.now() - time,
32
- list: filters,
33
- custom: loadTable?.filterCustom?.map(el => ({ label: el.label })),
34
- inline: loadTable?.filterInline,
35
- state: loadTable?.filterState?.map(el => ({ label: el.label })),
36
- };
37
- }
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getSelect from './utils/getSelect.js';
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+
5
+ export default async function filter(req) {
6
+ const time = Date.now();
7
+
8
+ const {
9
+ params,
10
+ } = req;
11
+ const loadTable = await getTemplate('table', params.table);
12
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
13
+ const { columns } = await getMeta({ table: loadTable.table });
14
+
15
+ const filters = loadTable?.filters || loadTable?.filterList || [];
16
+ await Promise.all(filters.filter((el) => el.data).map(async (el) => {
17
+ const cls = await getSelect(el.data);
18
+ if (!cls?.arr || !loadTable.table) return;
19
+ const { dataTypeID } = columns.find((item) => item.name === el.id) || {};
20
+ const countArr = req.pg.pgType[dataTypeID]?.includes('[]')
21
+ ? await req.pg.queryCache(`select unnest(${el.id})::text as id,count(*) from ${loadTable.table} group by unnest(${el.id})`)
22
+ : await req.pg.queryCache(`select ${el.id}::text as id,count(*) from ${loadTable.table} group by ${el.id}`);
23
+
24
+ const options = countArr.rows.map(cel => {
25
+ const data = cls?.arr.find(c => c.id === cel.id);
26
+ return { ...cel, ...data };
27
+ });
28
+ Object.assign(el, { options });
29
+ }));
30
+ return {
31
+ time: Date.now() - time,
32
+ list: filters,
33
+ custom: loadTable?.filterCustom?.map(el => ({ label: el.label })),
34
+ inline: loadTable?.filterInline,
35
+ state: loadTable?.filterState?.map(el => ({ label: el.label })),
36
+ };
37
+ }
@@ -1,28 +1,28 @@
1
- import getTemplate from './utils/getTemplate.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
- const { pg, params } = req;
15
- const form = await getTemplate('form', params.form);
16
- if (!form) { return { status: 404, message: 'not found' }; }
17
-
18
- // replace settings
19
- const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
20
- if (arr?.length) {
21
- const string = JSON.stringify(form);
22
- const settings = await getSettings({ pg });
23
- const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
24
- const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
25
- return { time: Date.now() - time, form: JSON.parse(res) };
26
- }
27
- return { time: Date.now() - time, form };
28
- }
1
+ import getTemplate from './utils/getTemplate.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
+ const { pg, params } = req;
15
+ const form = await getTemplate('form', params.form);
16
+ if (!form) { return { status: 404, message: 'not found' }; }
17
+
18
+ // replace settings
19
+ const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
20
+ if (arr?.length) {
21
+ const string = JSON.stringify(form);
22
+ const settings = await getSettings({ pg });
23
+ const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
24
+ const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
25
+ return { time: Date.now() - time, form: JSON.parse(res) };
26
+ }
27
+ return { time: Date.now() - time, form };
28
+ }
@@ -1,72 +1,72 @@
1
- import getTemplate from './utils/getTemplate.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import metaFormat from '../funcs/metaFormat/index.js';
4
- import getTemplates from './utils/getTemplates.js';
5
-
6
- function sequence(tables, data, fn) {
7
- return tables.reduce((promise, table) => promise.then(() => fn({
8
- ...data, tableName: table.replace('.json', ''),
9
- })), Promise.resolve());
10
- }
11
-
12
- async function getData({
13
- pg, funcs, tableName, query = {}, maxLimit, res,
14
- }) {
15
- const loadTable = await getTemplate('table', tableName);
16
-
17
- if (!loadTable) { return { message: 'not found', status: 404 }; }
18
-
19
- const { table, columns, meta, ua } = loadTable;
20
-
21
- const { pk } = await getMeta(table);
22
-
23
- const cols = columns.map((el) => el.name || el).join(',');
24
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
25
- const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
26
-
27
- const limit = Math.max(maxLimit - res.rows.length, 0);
28
- // Math.max(query.offset - res.rows.length,0)
29
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
30
-
31
- const search = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
32
-
33
- const where = [!pk ? 'false' : 'true', loadTable.query, search].filter((el) => el);
34
- 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}`;
35
- if (query.sql) {
36
- res.sql.push(q);
37
- return;
38
- }
39
-
40
- const { rows } = await pg.query(q);
41
-
42
- const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
43
-
44
- await metaFormat({ rows, table: tableName });
45
- res.total += +total;
46
- rows.forEach((row) => {
47
- const href = meta?.href ? funcs.handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
48
- res.rows.push({ ...row, register: tableName, register_title: loadTable.ua, href });
49
- });
50
- }
51
-
52
- export default async function search({
53
- pg, funcs, query = {},
54
- }) {
55
- const time = Date.now();
56
-
57
- try {
58
- const tables = query.table ? [query.table] : await getTemplates('table');
59
- const res = { rows: [], sql: [], total: 0 };
60
-
61
- const maxLimit = Math.min(100, query.limit || '16');
62
- await sequence(tables, { pg, funcs, query, maxLimit, res }, getData);
63
-
64
- if (query.sql) return res.sql.join(';\n');
65
-
66
- return {
67
- time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
68
- };
69
- } catch (err) {
70
- return { error: err.toString(), status: 500 };
71
- }
72
- }
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import metaFormat from '../funcs/metaFormat/index.js';
4
+ import getTemplates from './utils/getTemplates.js';
5
+
6
+ function sequence(tables, data, fn) {
7
+ return tables.reduce((promise, table) => promise.then(() => fn({
8
+ ...data, tableName: table.replace('.json', ''),
9
+ })), Promise.resolve());
10
+ }
11
+
12
+ async function getData({
13
+ pg, funcs, tableName, query = {}, maxLimit, res,
14
+ }) {
15
+ const loadTable = await getTemplate('table', tableName);
16
+
17
+ if (!loadTable) { return { message: 'not found', status: 404 }; }
18
+
19
+ const { table, columns, meta, ua } = loadTable;
20
+
21
+ const { pk } = await getMeta(table);
22
+
23
+ const cols = columns.map((el) => el.name || el).join(',');
24
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
25
+ const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
26
+
27
+ const limit = Math.max(maxLimit - res.rows.length, 0);
28
+ // Math.max(query.offset - res.rows.length,0)
29
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
30
+
31
+ const search = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
32
+
33
+ const where = [!pk ? 'false' : 'true', loadTable.query, search].filter((el) => el);
34
+ 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}`;
35
+ if (query.sql) {
36
+ res.sql.push(q);
37
+ return;
38
+ }
39
+
40
+ const { rows } = await pg.query(q);
41
+
42
+ const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
43
+
44
+ await metaFormat({ rows, table: tableName });
45
+ res.total += +total;
46
+ rows.forEach((row) => {
47
+ const href = meta?.href ? funcs.handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
48
+ res.rows.push({ ...row, register: tableName, register_title: loadTable.ua, href });
49
+ });
50
+ }
51
+
52
+ export default async function search({
53
+ pg, funcs, query = {},
54
+ }) {
55
+ const time = Date.now();
56
+
57
+ try {
58
+ const tables = query.table ? [query.table] : await getTemplates('table');
59
+ const res = { rows: [], sql: [], total: 0 };
60
+
61
+ const maxLimit = Math.min(100, query.limit || '16');
62
+ await sequence(tables, { pg, funcs, query, maxLimit, res }, getData);
63
+
64
+ if (query.sql) return res.sql.join(';\n');
65
+
66
+ return {
67
+ time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
68
+ };
69
+ } catch (err) {
70
+ return { error: err.toString(), status: 500 };
71
+ }
72
+ }
@@ -1,6 +1,8 @@
1
1
  import getSelectMeta from './utils/getSelectMeta.js';
2
2
  import getPG from '../../pg/funcs/getPG.js';
3
3
  import config from '../../config.js';
4
+ import getTemplate from './utils/getTemplate.js';
5
+ import getTableSql from '../funcs/getFilterSQL/util/getTableSql.js';
4
6
 
5
7
  const limit = 50;
6
8
  const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Cache-Control': 'no-cache' };
@@ -12,10 +14,25 @@ export default async function suggest(req) {
12
14
  const time = Date.now();
13
15
  const parent = query.parent || '';
14
16
 
17
+ const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
15
18
  const selectName = query.sel || query.name || params.data;
16
19
  if (!selectName) return { headers, status: 400, message: 'name is required' };
17
20
 
18
- const meta = await getSelectMeta({ name: selectName });
21
+ const body = await getTemplate('table', table);
22
+ if (table && !pg1.pk[body?.table || table]) {
23
+ return { headers, status: 400, message: 'param name is invalid: 1' };
24
+ }
25
+ const columnExists = true;
26
+ if (table && (!column || !columnExists)) {
27
+ return { headers, status: 400, message: 'param name is invalid: 2' };
28
+ }
29
+
30
+ const meta = table && column
31
+ ? {
32
+ original: `with c(id,text) as (select row_number() over(), ${column} from ${body?.table || table} group by ${column} ) select * from c`,
33
+ searchQuery: '("text" ilike $1 )',
34
+ }
35
+ : await getSelectMeta({ name: selectName });
19
36
  const pg = meta?.db ? getPG(meta.db) : pg1;
20
37
  if (!meta) return { headers, status: 404, message: 'Not found query select ' };
21
38
  if (query.meta) return meta;
@@ -1,20 +1,20 @@
1
- import getTemplate from './getTemplate.js';
2
-
3
- const loadCls = {};
4
-
5
- export default async function getTable(name) {
6
- if (loadCls[name]) return loadCls[name];
7
-
8
- const clsData = await getTemplate('cls', name);
9
-
10
- if (clsData) {
11
- loadCls[name] = { arr: clsData };
12
- return loadCls[name];
13
- }
14
-
15
- const selectData = await getTemplate('select', name);
16
- if (!selectData) { return null; }
17
-
18
- loadCls[name] = selectData;
19
- return loadCls[name];
20
- }
1
+ import getTemplate from './getTemplate.js';
2
+
3
+ const loadCls = {};
4
+
5
+ export default async function getSelect(name) {
6
+ if (loadCls[name]) return loadCls[name];
7
+
8
+ const clsData = await getTemplate('cls', name);
9
+
10
+ if (clsData) {
11
+ loadCls[name] = { arr: clsData };
12
+ return loadCls[name];
13
+ }
14
+
15
+ const selectData = await getTemplate('select', name);
16
+ if (!selectData) { return null; }
17
+
18
+ loadCls[name] = selectData;
19
+ return loadCls[name];
20
+ }