@opengis/fastify-table 1.1.78 → 1.1.79

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 (77) hide show
  1. package/index.js +76 -76
  2. package/package.json +45 -45
  3. package/server/migrations/0.sql +80 -80
  4. package/server/migrations/cls.sql +39 -39
  5. package/server/migrations/context.sql +95 -0
  6. package/server/migrations/properties.sql +144 -144
  7. package/server/migrations/roles.sql +179 -175
  8. package/server/migrations/users.sql +170 -170
  9. package/server/plugins/cron/funcs/addCron.js +130 -130
  10. package/server/plugins/cron/index.js +6 -6
  11. package/server/plugins/crud/funcs/dataDelete.js +21 -21
  12. package/server/plugins/crud/funcs/dataInsert.js +38 -38
  13. package/server/plugins/crud/funcs/dataUpdate.js +50 -50
  14. package/server/plugins/crud/funcs/getAccess.js +48 -48
  15. package/server/plugins/crud/funcs/getOpt.js +13 -13
  16. package/server/plugins/crud/funcs/setOpt.js +21 -21
  17. package/server/plugins/crud/funcs/setToken.js +44 -44
  18. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  19. package/server/plugins/crud/funcs/utils/logChanges.js +62 -62
  20. package/server/plugins/crud/index.js +23 -23
  21. package/server/plugins/hook/index.js +8 -8
  22. package/server/plugins/logger/errorStatus.js +19 -19
  23. package/server/plugins/logger/index.js +21 -21
  24. package/server/plugins/migration/funcs/exec.migrations.js +79 -79
  25. package/server/plugins/migration/index.js +7 -7
  26. package/server/plugins/pg/funcs/getMeta.js +28 -28
  27. package/server/plugins/pg/funcs/getPG.js +33 -33
  28. package/server/plugins/pg/pgClients.js +21 -21
  29. package/server/plugins/policy/funcs/checkPolicy.js +92 -92
  30. package/server/plugins/policy/funcs/checkXSS.js +1 -1
  31. package/server/plugins/policy/index.js +12 -12
  32. package/server/plugins/policy/sqlInjection.js +33 -33
  33. package/server/plugins/redis/client.js +8 -8
  34. package/server/plugins/redis/funcs/redisClients.js +3 -3
  35. package/server/plugins/redis/index.js +17 -17
  36. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  37. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  38. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +170 -170
  39. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  40. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  41. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  42. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  43. package/server/plugins/table/funcs/getSelect.js +19 -19
  44. package/server/plugins/table/funcs/getSelectMeta.js +60 -60
  45. package/server/plugins/table/funcs/getTemplates.js +19 -19
  46. package/server/plugins/table/funcs/gisIRColumn.js +72 -72
  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/metaFormat/getSelectVal.js +38 -22
  50. package/server/plugins/table/funcs/metaFormat/index.js +31 -30
  51. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  52. package/server/plugins/table/index.js +13 -13
  53. package/server/plugins/util/funcs/eventStream.js +28 -28
  54. package/server/plugins/util/index.js +7 -7
  55. package/server/routes/cron/index.js +14 -14
  56. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  57. package/server/routes/crud/controllers/insert.js +80 -80
  58. package/server/routes/crud/controllers/table.js +91 -91
  59. package/server/routes/crud/controllers/update.js +82 -82
  60. package/server/routes/crud/index.js +21 -21
  61. package/server/routes/logger/controllers/logger.file.js +92 -92
  62. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  63. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  64. package/server/routes/logger/index.js +17 -17
  65. package/server/routes/properties/controllers/properties.add.js +55 -55
  66. package/server/routes/properties/controllers/properties.get.js +17 -17
  67. package/server/routes/properties/index.js +16 -16
  68. package/server/routes/table/controllers/data.js +144 -144
  69. package/server/routes/table/controllers/filter.js +60 -60
  70. package/server/routes/table/controllers/form.js +42 -42
  71. package/server/routes/table/controllers/search.js +74 -74
  72. package/server/routes/table/controllers/suggest.js +84 -84
  73. package/server/routes/table/index.js +28 -28
  74. package/server/routes/table/schema.js +64 -64
  75. package/server/routes/util/controllers/status.monitor.js +8 -8
  76. package/server/routes/util/index.js +11 -11
  77. package/utils.js +122 -122
@@ -1,92 +1,92 @@
1
- import { config } from '@opengis/fastify-table/utils.js';
2
- import block from '../sqlInjection.js';
3
-
4
- /**
5
- * Middleware func
6
- *
7
- * @type function
8
- * @alias checkPolicy
9
- * @summary Функція дозволяє налаштувати доступ до сайту або API для адмін. та публічної частини веб-ресурсу
10
- * @param {String} path - назва апі
11
- * @returns {object|null} Returns object
12
- */
13
-
14
- export default function checkPolicy(req) {
15
- const {
16
- originalUrl: path, hostname, query, params, headers: hs, log, sid = 35,
17
- } = req;
18
- const user = req.user || req.session?.passport?.user;
19
-
20
- const isUser = config?.debug || !!user;
21
-
22
- const isServer = process.argv[2];
23
- const { policy = [] } = req.routeOptions?.config || {};
24
-
25
- /*= == 0.Check superadmin access === */
26
- if (policy.includes('superadmin') && user?.user_type !== 'superadmin') {
27
- log.warn('api/superadmin', {
28
- path, params, query, body: JSON.stringify(req?.body || {}).substring(30), message: 'access restricted: 0',
29
- });
30
- return { message: 'access restricted: 0', status: 403 };
31
- }
32
-
33
- /*= == 1.File injection === */
34
- if (JSON.stringify(params || {})?.includes('../') || JSON.stringify(query || {})?.includes('../') || path?.includes('../')) {
35
- log.warn('injection/file', {
36
- path, params, query, message: 'access restricted: 1',
37
- });
38
- return { message: 'access restricted: 1', status: 403 };
39
- }
40
-
41
- /* === 1.1 File === */
42
- const allowExtPublic = ['.png', '.jpg', '.svg'];
43
- const ext = path.toLowerCase().substr(-4);
44
- if (path.includes('files/') && allowExtPublic.includes(ext)) return null;
45
-
46
- /* === 2.SQL Injection policy: no-sql === */
47
- if (!policy.includes('no-sql')) {
48
- // skip polyline param - data filter (geometry bounds)
49
- const stopWords = block.filter((el) => path.replace(query.polyline, '').includes(el));
50
- if (stopWords?.length) {
51
- log.warn('injection/sql', { stopWords, message: 'access restricted: 2', path });
52
- return { message: 'access restricted: 2', status: 403 };
53
- }
54
- }
55
- /* policy: skip if not API */
56
- const isApi = ['/files/', '/api/format/', '/api', '/api-user/', '/logger', '/file/'].filter((el) => path.includes(el)).length;
57
- if (!isApi) {
58
- return null;
59
- }
60
-
61
- /* === policy: public === */
62
- if (policy.includes('public')) {
63
- return null;
64
- }
65
-
66
- /* === 3. policy: user === */
67
- if (!user && policy.includes('user') && false) {
68
- log.warn('policy/user', { message: 'access restricted: 3', path });
69
- return { message: 'access restricted: 3', status: 403 };
70
- }
71
-
72
- /* === 4. policy: referer === */
73
- if (!hs?.referer?.includes?.(hostname) && policy.includes('referer') && !config.local && !config.debug) {
74
- log.warn('policy/referer', { message: 'access restricted: 4', uid: user?.uid });
75
- return { message: 'access restricted: 4', status: 403 };
76
- }
77
-
78
- /* === 5. policy: site auth === */
79
- if (!policy.includes('site') && sid === 1 && isUser && !config.local && !config.debug) {
80
- log.warn('policy/site', { message: 'access restricted: 5', path, uid: user?.uid });
81
- return { message: 'access restricted: 5', status: 403 };
82
- }
83
-
84
- /* === 6. base policy: block api, except login === */
85
- if (sid === 35 && !isUser && isServer && !config.local && !config.debug
86
- && !path.startsWith(`${config.prefix || '/api'}/login`)) {
87
- log.warn('policy/api', { message: 'access restricted: 6', path, uid: user?.uid });
88
- return { message: 'access restricted: 6', status: 403 };
89
- }
90
-
91
- return null;
92
- }
1
+ import { config } from '@opengis/fastify-table/utils.js';
2
+ import block from '../sqlInjection.js';
3
+
4
+ /**
5
+ * Middleware func
6
+ *
7
+ * @type function
8
+ * @alias checkPolicy
9
+ * @summary Функція дозволяє налаштувати доступ до сайту або API для адмін. та публічної частини веб-ресурсу
10
+ * @param {String} path - назва апі
11
+ * @returns {object|null} Returns object
12
+ */
13
+
14
+ export default function checkPolicy(req) {
15
+ const {
16
+ originalUrl: path, hostname, query, params, headers: hs, log, sid = 35,
17
+ } = req;
18
+ const user = req.user || req.session?.passport?.user;
19
+
20
+ const isUser = config?.debug || !!user;
21
+
22
+ const isServer = process.argv[2];
23
+ const { policy = [] } = req.routeOptions?.config || {};
24
+
25
+ /*= == 0.Check superadmin access === */
26
+ if (policy.includes('superadmin') && user?.user_type !== 'superadmin') {
27
+ log.warn('api/superadmin', {
28
+ path, params, query, body: JSON.stringify(req?.body || {}).substring(30), message: 'access restricted: 0',
29
+ });
30
+ return { message: 'access restricted: 0', status: 403 };
31
+ }
32
+
33
+ /*= == 1.File injection === */
34
+ if (JSON.stringify(params || {})?.includes('../') || JSON.stringify(query || {})?.includes('../') || path?.includes('../')) {
35
+ log.warn('injection/file', {
36
+ path, params, query, message: 'access restricted: 1',
37
+ });
38
+ return { message: 'access restricted: 1', status: 403 };
39
+ }
40
+
41
+ /* === 1.1 File === */
42
+ const allowExtPublic = ['.png', '.jpg', '.svg'];
43
+ const ext = path.toLowerCase().substr(-4);
44
+ if (path.includes('files/') && allowExtPublic.includes(ext)) return null;
45
+
46
+ /* === 2.SQL Injection policy: no-sql === */
47
+ if (!policy.includes('no-sql')) {
48
+ // skip polyline param - data filter (geometry bounds)
49
+ const stopWords = block.filter((el) => path.replace(query.polyline, '').includes(el));
50
+ if (stopWords?.length) {
51
+ log.warn('injection/sql', { stopWords, message: 'access restricted: 2', path });
52
+ return { message: 'access restricted: 2', status: 403 };
53
+ }
54
+ }
55
+ /* policy: skip if not API */
56
+ const isApi = ['/files/', '/api/format/', '/api', '/api-user/', '/logger', '/file/'].filter((el) => path.includes(el)).length;
57
+ if (!isApi) {
58
+ return null;
59
+ }
60
+
61
+ /* === policy: public === */
62
+ if (policy.includes('public')) {
63
+ return null;
64
+ }
65
+
66
+ /* === 3. policy: user === */
67
+ if (!user && policy.includes('user') && false) {
68
+ log.warn('policy/user', { message: 'access restricted: 3', path });
69
+ return { message: 'access restricted: 3', status: 403 };
70
+ }
71
+
72
+ /* === 4. policy: referer === */
73
+ if (!hs?.referer?.includes?.(hostname) && policy.includes('referer') && !config.local && !config.debug) {
74
+ log.warn('policy/referer', { message: 'access restricted: 4', uid: user?.uid });
75
+ return { message: 'access restricted: 4', status: 403 };
76
+ }
77
+
78
+ /* === 5. policy: site auth === */
79
+ if (!policy.includes('site') && sid === 1 && isUser && !config.local && !config.debug) {
80
+ log.warn('policy/site', { message: 'access restricted: 5', path, uid: user?.uid });
81
+ return { message: 'access restricted: 5', status: 403 };
82
+ }
83
+
84
+ /* === 6. base policy: block api, except login === */
85
+ if (sid === 35 && !isUser && isServer && !config.local && !config.debug
86
+ && !path.startsWith(`${config.prefix || '/api'}/login`)) {
87
+ log.warn('policy/api', { message: 'access restricted: 6', path, uid: user?.uid });
88
+ return { message: 'access restricted: 6', status: 403 };
89
+ }
90
+
91
+ return null;
92
+ }
@@ -31,7 +31,7 @@ function checkXSS({ body, schema = {} }) {
31
31
  }); */
32
32
 
33
33
  const field = Object.keys(body)
34
- ?.find((key) => body[key]
34
+ ?.find((key) => body[key]?.toLowerCase
35
35
  && !disabledCheckFields.includes(key)
36
36
  && body[key].toLowerCase().includes(stopWords[0]));
37
37
  if (field) {
@@ -1,12 +1,12 @@
1
- import checkPolicy from './funcs/checkPolicy.js';
2
-
3
- async function plugin(fastify) {
4
- fastify.addHook('preParsing', async (request, reply) => {
5
- const hookData = checkPolicy(request);
6
- if (hookData?.status && hookData?.message) {
7
- return reply.status(hookData?.status).send(hookData.message);
8
- }
9
- });
10
- }
11
-
12
- export default plugin;
1
+ import checkPolicy from './funcs/checkPolicy.js';
2
+
3
+ async function plugin(fastify) {
4
+ fastify.addHook('preParsing', async (request, reply) => {
5
+ const hookData = checkPolicy(request);
6
+ if (hookData?.status && hookData?.message) {
7
+ return reply.status(hookData?.status).send(hookData.message);
8
+ }
9
+ });
10
+ }
11
+
12
+ export default plugin;
@@ -1,33 +1,33 @@
1
- const sqlInjection = [
2
- '()',
3
- '^',
4
- '*',
5
- 'like ',
6
- '@variable',
7
- '@@variable',
8
- 'group by ',
9
- 'union ',
10
- 'select ',
11
- 'having ',
12
- 'as injectx',
13
- 'where ',
14
- 'rlike ',
15
- 'if(',
16
- 'sleep(',
17
- 'waitfor delay',
18
- 'benchmark(',
19
- 'pg_sleep(',
20
- "'\\\"",
21
- 'randomblob(',
22
- 'order by ',
23
- 'union all ',
24
- '+or',
25
- 'or ',
26
- 'and ',
27
- "'' ",
28
- '""" ',
29
- '<script',
30
- 'javascript:',
31
- ];
32
-
33
- export default sqlInjection;
1
+ const sqlInjection = [
2
+ '()',
3
+ '^',
4
+ '*',
5
+ 'like ',
6
+ '@variable',
7
+ '@@variable',
8
+ 'group by ',
9
+ 'union ',
10
+ 'select ',
11
+ 'having ',
12
+ 'as injectx',
13
+ 'where ',
14
+ 'rlike ',
15
+ 'if(',
16
+ 'sleep(',
17
+ 'waitfor delay',
18
+ 'benchmark(',
19
+ 'pg_sleep(',
20
+ "'\\\"",
21
+ 'randomblob(',
22
+ 'order by ',
23
+ 'union all ',
24
+ '+or',
25
+ 'or ',
26
+ 'and ',
27
+ "'' ",
28
+ '""" ',
29
+ '<script',
30
+ 'javascript:',
31
+ ];
32
+
33
+ export default sqlInjection;
@@ -1,8 +1,8 @@
1
- import redisClients from './funcs/redisClients.js';
2
- import getRedis from './funcs/getRedis.js';
3
-
4
- if (!redisClients[0]) {
5
- getRedis({ db: 0 });
6
- }
7
-
8
- export default redisClients[0];
1
+ import redisClients from './funcs/redisClients.js';
2
+ import getRedis from './funcs/getRedis.js';
3
+
4
+ if (!redisClients[0]) {
5
+ getRedis({ db: 0 });
6
+ }
7
+
8
+ export default redisClients[0];
@@ -1,3 +1,3 @@
1
- const redisClients = {};
2
-
3
- export default redisClients;
1
+ const redisClients = {};
2
+
3
+ export default redisClients;
@@ -1,17 +1,17 @@
1
- // import redis from './client.js';
2
- import redisClients from './funcs/redisClients.js';
3
-
4
- function close(fastify) {
5
- // redis.quit();
6
- Object.keys(redisClients).forEach((key) => redisClients[key].quit());
7
- }
8
-
9
- async function plugin(fastify) {
10
- // const client = getRedis({ db: 0 });
11
- // client.getJSON = client.get;
12
- // fastify.decorate('rclient', client);
13
- // fastify.decorate('getRedis', getRedis);
14
- fastify.addHook('onClose', close);
15
- }
16
-
17
- export default plugin;
1
+ // import redis from './client.js';
2
+ import redisClients from './funcs/redisClients.js';
3
+
4
+ function close(fastify) {
5
+ // redis.quit();
6
+ Object.keys(redisClients).forEach((key) => redisClients[key].quit());
7
+ }
8
+
9
+ async function plugin(fastify) {
10
+ // const client = getRedis({ db: 0 });
11
+ // client.getJSON = client.get;
12
+ // fastify.decorate('rclient', client);
13
+ // fastify.decorate('getRedis', getRedis);
14
+ fastify.addHook('onClose', close);
15
+ }
16
+
17
+ export default plugin;
@@ -1,8 +1,8 @@
1
- import userTemplateDir from './userTemplateDir.js';
2
-
3
- export default function addTemplateDir(dir) {
4
- if (dir) {
5
- userTemplateDir.push(dir);
6
- }
7
- return userTemplateDir;
8
- }
1
+ import userTemplateDir from './userTemplateDir.js';
2
+
3
+ export default function addTemplateDir(dir) {
4
+ if (dir) {
5
+ userTemplateDir.push(dir);
6
+ }
7
+ return userTemplateDir;
8
+ }
@@ -1,96 +1,96 @@
1
- import getTemplate from '../getTemplate.js';
2
- import pgClients from '../../../pg/pgClients.js';
3
-
4
- // import { getTemplate, pgClients } from '../../../../../utils.js';
5
-
6
- // filter util
7
- import getTableSql from './util/getTableSql.js';
8
- import getFilterQuery from './util/getFilterQuery.js';
9
- import getOptimizedQuery from './util/getOptimizedQuery.js';
10
-
11
- async function getFilterSQL({
12
- table, filter, pg = pgClients.client, search, filterList, query, custom, state,
13
- }) {
14
- if (!table) return { error: 'param table is required', status: 400 };
15
-
16
- const body = await getTemplate('table', table);
17
-
18
- const sqlList = body?.sql?.length
19
- ? body?.sql?.filter((el) => !el.disabled && el?.sql?.replace)
20
- .map((el, i) => {
21
- Object.assign(el, { name: el.name || `t${i + 1}` });
22
- return ` left join lateral (${el.filter ? el.sql.replace(/limit 1/ig, '') : el.sql}) as ${el.name} on 1=1 `;
23
- }).join(' ')
24
- : '';
25
- const fieldQuery = `select * from ${body?.table || table} ${sqlList ? ` t ${sqlList}` : ''} where 1=1 limit 0`;
26
- const { fields = [] } = await pg.query(fieldQuery);
27
-
28
- const { fields: fieldsModel } = body?.table && pg.pk[body?.table] ? await pg.query(`select * from ${body.table} limit 0`) : {};
29
-
30
- const autoSearchColumn = fields?.filter((el) => pg.pgType?.[el.dataTypeID] === 'text')?.map((el) => el.name).join(',');
31
- const searchColumn = body?.search_column || autoSearchColumn;
32
- const fieldsList = (fieldsModel || fields)?.map((el) => el.name);
33
- try {
34
- const tableSQL = await getTableSql({
35
- pg, body, table, fields,
36
- });
37
- const sval = `ilike '%${decodeURIComponent(search).replace(/'/g, "''")}%'`;
38
- const searchQuery = search && searchColumn
39
- ? ` (${searchColumn.split(',')?.map((name) => {
40
- const { pk } = tableSQL.find((el) => el.name === name) || {};
41
- return pk && !fieldsList.includes(name) ? `${pk} in (select ${pk} from (${fieldQuery})q where ${name} ${sval})` : `${name} ${sval}`;
42
- }).join(' or ')} )` : '';
43
-
44
- const filterList1 = await Promise.all((filterList || (body?.filter_list || []).concat(body?.filterInline || []).concat(body?.filterCustom || []).concat(body?.filterState || []).concat(body?.filterList || [])
45
- .concat(body?.filters || [])) /* .concat(extraFilters || []).concat(customFilters || []) */
46
-
47
- ?.map(async (el) => {
48
- if (!el?.data) return el;
49
- const cls = await getTemplate(['cls', 'select'], el.data);
50
- if (Array.isArray(cls) && cls?.length) {
51
- Object.assign(el, { options: cls });
52
- }
53
- else if (typeof (cls?.sql || cls) === 'string') {
54
- Object.assign(el, { sql: cls?.sql || cls });
55
- }
56
- return el;
57
- }));
58
-
59
- const filters = getFilterQuery({
60
- pg,
61
- filter,
62
- table,
63
- tableSQL,
64
- fields,
65
- filterList: filterList1,
66
- });
67
-
68
- // filter
69
- const customQuery = body?.filterCustom?.length && custom ? body.filterCustom?.find((el) => el.name === custom)?.sql : null;
70
- const stateQuery = body?.filterState?.length && state ? body.filterState?.find((el) => el.name === state)?.sql : null;
71
-
72
- const filterQuery = filters?.filter((el) => el.query)?.map((el) => `${el.query} `).join(' and ');
73
- const q = [body?.query, query, searchQuery, filterQuery, stateQuery, customQuery].filter((el) => el).join(' and ');
74
-
75
- // table
76
- const modelQuery = body?.model || body?.table || table;
77
- const optimizedSQL = `select * from ${getOptimizedQuery({ body, table, q })} `;
78
- const tableCount = getOptimizedQuery({ body, table, q }, true);
79
- // console.log(optimizedSQL);
80
- return {
81
- filterList,
82
-
83
- q,
84
- optimizedSQL,
85
- tableCount,
86
- table: modelQuery,
87
- // filter parts
88
- searchQuery,
89
- };
90
- }
91
- catch (err) {
92
- throw new Error(err.toString());
93
- }
94
- }
95
-
96
- export default getFilterSQL;
1
+ import getTemplate from '../getTemplate.js';
2
+ import pgClients from '../../../pg/pgClients.js';
3
+
4
+ // import { getTemplate, pgClients } from '../../../../../utils.js';
5
+
6
+ // filter util
7
+ import getTableSql from './util/getTableSql.js';
8
+ import getFilterQuery from './util/getFilterQuery.js';
9
+ import getOptimizedQuery from './util/getOptimizedQuery.js';
10
+
11
+ async function getFilterSQL({
12
+ table, filter, pg = pgClients.client, search, filterList, query, custom, state,
13
+ }) {
14
+ if (!table) return { error: 'param table is required', status: 400 };
15
+
16
+ const body = await getTemplate('table', table);
17
+
18
+ const sqlList = body?.sql?.length
19
+ ? body?.sql?.filter((el) => !el.disabled && el?.sql?.replace)
20
+ .map((el, i) => {
21
+ Object.assign(el, { name: el.name || `t${i + 1}` });
22
+ return ` left join lateral (${el.filter ? el.sql.replace(/limit 1/ig, '') : el.sql}) as ${el.name} on 1=1 `;
23
+ }).join(' ')
24
+ : '';
25
+ const fieldQuery = `select * from ${body?.table || table} ${sqlList ? ` t ${sqlList}` : ''} where 1=1 limit 0`;
26
+ const { fields = [] } = await pg.query(fieldQuery);
27
+
28
+ const { fields: fieldsModel } = body?.table && pg.pk[body?.table] ? await pg.query(`select * from ${body.table} limit 0`) : {};
29
+
30
+ const autoSearchColumn = fields?.filter((el) => pg.pgType?.[el.dataTypeID] === 'text')?.map((el) => el.name).join(',');
31
+ const searchColumn = body?.search_column || autoSearchColumn;
32
+ const fieldsList = (fieldsModel || fields)?.map((el) => el.name);
33
+ try {
34
+ const tableSQL = await getTableSql({
35
+ pg, body, table, fields,
36
+ });
37
+ const sval = `ilike '%${decodeURIComponent(search).replace(/'/g, "''")}%'`;
38
+ const searchQuery = search && searchColumn
39
+ ? ` (${searchColumn.split(',')?.map((name) => {
40
+ const { pk } = tableSQL.find((el) => el.name === name) || {};
41
+ return pk && !fieldsList.includes(name) ? `${pk} in (select ${pk} from (${fieldQuery})q where ${name} ${sval})` : `${name} ${sval}`;
42
+ }).join(' or ')} )` : '';
43
+
44
+ const filterList1 = await Promise.all((filterList || (body?.filter_list || []).concat(body?.filterInline || []).concat(body?.filterCustom || []).concat(body?.filterState || []).concat(body?.filterList || [])
45
+ .concat(body?.filters || [])) /* .concat(extraFilters || []).concat(customFilters || []) */
46
+
47
+ ?.map(async (el) => {
48
+ if (!el?.data) return el;
49
+ const cls = await getTemplate(['cls', 'select'], el.data);
50
+ if (Array.isArray(cls) && cls?.length) {
51
+ Object.assign(el, { options: cls });
52
+ }
53
+ else if (typeof (cls?.sql || cls) === 'string') {
54
+ Object.assign(el, { sql: cls?.sql || cls });
55
+ }
56
+ return el;
57
+ }));
58
+
59
+ const filters = getFilterQuery({
60
+ pg,
61
+ filter,
62
+ table,
63
+ tableSQL,
64
+ fields,
65
+ filterList: filterList1,
66
+ });
67
+
68
+ // filter
69
+ const customQuery = body?.filterCustom?.length && custom ? body.filterCustom?.find((el) => el.name === custom)?.sql : null;
70
+ const stateQuery = body?.filterState?.length && state ? body.filterState?.find((el) => el.name === state)?.sql : null;
71
+
72
+ const filterQuery = filters?.filter((el) => el.query)?.map((el) => `${el.query} `).join(' and ');
73
+ const q = [body?.query, query, searchQuery, filterQuery, stateQuery, customQuery].filter((el) => el).join(' and ');
74
+
75
+ // table
76
+ const modelQuery = body?.model || body?.table || table;
77
+ const optimizedSQL = `select * from ${getOptimizedQuery({ body, table, q })} `;
78
+ const tableCount = getOptimizedQuery({ body, table, q }, true);
79
+ // console.log(optimizedSQL);
80
+ return {
81
+ filterList,
82
+
83
+ q,
84
+ optimizedSQL,
85
+ tableCount,
86
+ table: modelQuery,
87
+ // filter parts
88
+ searchQuery,
89
+ };
90
+ }
91
+ catch (err) {
92
+ throw new Error(err.toString());
93
+ }
94
+ }
95
+
96
+ export default getFilterSQL;