@opengis/fastify-table 1.1.133 → 1.1.135

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 (70) hide show
  1. package/README.md +86 -86
  2. package/index.js +78 -78
  3. package/package.json +1 -1
  4. package/server/migrations/0.sql +80 -80
  5. package/server/migrations/cls.sql +39 -39
  6. package/server/migrations/context.sql +94 -94
  7. package/server/migrations/properties.sql +144 -144
  8. package/server/migrations/users.sql +173 -173
  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 +23 -23
  12. package/server/plugins/crud/funcs/dataInsert.js +45 -45
  13. package/server/plugins/crud/funcs/dataUpdate.js +65 -65
  14. package/server/plugins/crud/funcs/getOpt.js +13 -13
  15. package/server/plugins/crud/funcs/setOpt.js +21 -21
  16. package/server/plugins/crud/funcs/setToken.js +44 -44
  17. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  18. package/server/plugins/crud/funcs/utils/logChanges.js +62 -62
  19. package/server/plugins/crud/index.js +23 -23
  20. package/server/plugins/hook/index.js +8 -8
  21. package/server/plugins/logger/errorStatus.js +19 -19
  22. package/server/plugins/logger/index.js +21 -21
  23. package/server/plugins/migration/funcs/exec.migrations.js +86 -86
  24. package/server/plugins/migration/index.js +7 -7
  25. package/server/plugins/pg/funcs/getPG.js +1 -0
  26. package/server/plugins/pg/pgClients.js +21 -21
  27. package/server/plugins/policy/index.js +12 -12
  28. package/server/plugins/policy/sqlInjection.js +33 -33
  29. package/server/plugins/redis/client.js +8 -8
  30. package/server/plugins/redis/funcs/redisClients.js +3 -3
  31. package/server/plugins/redis/index.js +17 -17
  32. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  33. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  34. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +171 -171
  35. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  36. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  37. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  38. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  39. package/server/plugins/table/funcs/getSelect.js +29 -29
  40. package/server/plugins/table/funcs/getTemplates.js +19 -19
  41. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  42. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  43. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  44. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +50 -50
  45. package/server/plugins/table/funcs/metaFormat/index.js +45 -45
  46. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  47. package/server/plugins/table/index.js +13 -13
  48. package/server/plugins/util/funcs/eventStream.js +1 -1
  49. package/server/plugins/util/index.js +7 -7
  50. package/server/routes/cron/index.js +14 -14
  51. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  52. package/server/routes/crud/controllers/insert.js +3 -2
  53. package/server/routes/crud/controllers/table.js +91 -91
  54. package/server/routes/logger/controllers/logger.file.js +92 -92
  55. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  56. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  57. package/server/routes/logger/index.js +17 -17
  58. package/server/routes/properties/controllers/properties.add.js +55 -55
  59. package/server/routes/properties/controllers/properties.get.js +17 -17
  60. package/server/routes/properties/index.js +16 -16
  61. package/server/routes/table/controllers/data.js +156 -156
  62. package/server/routes/table/controllers/filter.js +66 -66
  63. package/server/routes/table/controllers/form.js +42 -42
  64. package/server/routes/table/controllers/search.js +74 -74
  65. package/server/routes/table/controllers/suggest.js +158 -158
  66. package/server/routes/table/index.js +29 -29
  67. package/server/routes/table/schema.js +64 -64
  68. package/server/routes/util/controllers/status.monitor.js +8 -8
  69. package/server/routes/util/index.js +11 -11
  70. package/utils.js +122 -122
@@ -1,19 +1,19 @@
1
- import config from '../../../../../config.js';
2
-
3
- /**
4
- *
5
- * @summary check user access to logger interface - per admin user type or user group
6
- * @returns {Object} message, status
7
- */
8
-
9
- export default function checkUserAccess({ user = {} }) {
10
- // console.log(user);
11
- if (user.user_type !== 'admin' && !config?.local) {
12
- return { message: 'access restricted', status: 403 };
13
- }
14
-
15
- /* if (!['admin', 'superadmin']?.includes(user.user_type) && count === '0') {
16
- return { message: 'access restricted', status: 403 };
17
- } */
18
- return { message: 'access granted', status: 200 };
19
- }
1
+ import config from '../../../../../config.js';
2
+
3
+ /**
4
+ *
5
+ * @summary check user access to logger interface - per admin user type or user group
6
+ * @returns {Object} message, status
7
+ */
8
+
9
+ export default function checkUserAccess({ user = {} }) {
10
+ // console.log(user);
11
+ if (user.user_type !== 'admin' && !config?.local) {
12
+ return { message: 'access restricted', status: 403 };
13
+ }
14
+
15
+ /* if (!['admin', 'superadmin']?.includes(user.user_type) && count === '0') {
16
+ return { message: 'access restricted', status: 403 };
17
+ } */
18
+ return { message: 'access granted', status: 200 };
19
+ }
@@ -1,26 +1,26 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- import config from '../../../../../config.js';
5
-
6
- // import { existsSync } from 'fs';
7
- let logDir = null;
8
- export default function getRootDir() {
9
- // absolute / relative path
10
- if (logDir) return logDir;
11
- const file = ['config.json', '/data/local/config.json'].find(el => (fs.existsSync(el) ? el : null));
12
- const root = file === 'config.json' ? process.cwd() : '/data/local';
13
- logDir = config.logDir || path.join(root, config.log?.dir || 'log');
14
- console.log({ logDir });
15
- return logDir;
16
-
17
- // windows debug support
18
- /* const customLogDir = process.cwd().includes(':') ? 'c:/data/local' : '/data/local';
19
- // docker default path
20
- if (existsSync(customLogDir)) {
21
- return path.join(customLogDir, config.folder || '', 'log');
22
- }
23
-
24
- // non-docker default path
25
- return path.join(config.root || '/data/local', config.folder || '', 'log'); */
26
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import config from '../../../../../config.js';
5
+
6
+ // import { existsSync } from 'fs';
7
+ let logDir = null;
8
+ export default function getRootDir() {
9
+ // absolute / relative path
10
+ if (logDir) return logDir;
11
+ const file = ['config.json', '/data/local/config.json'].find(el => (fs.existsSync(el) ? el : null));
12
+ const root = file === 'config.json' ? process.cwd() : '/data/local';
13
+ logDir = config.logDir || path.join(root, config.log?.dir || 'log');
14
+ console.log({ logDir });
15
+ return logDir;
16
+
17
+ // windows debug support
18
+ /* const customLogDir = process.cwd().includes(':') ? 'c:/data/local' : '/data/local';
19
+ // docker default path
20
+ if (existsSync(customLogDir)) {
21
+ return path.join(customLogDir, config.folder || '', 'log');
22
+ }
23
+
24
+ // non-docker default path
25
+ return path.join(config.root || '/data/local', config.folder || '', 'log'); */
26
+ }
@@ -1,17 +1,17 @@
1
- import loggerFile from './controllers/logger.file.js';
2
-
3
- // import loggerTest from './controllers/logger.test.api.js';
4
-
5
- const loggerSchema = {
6
- querystring: {
7
- download: { type: 'string', pattern: '^(\\d+)$' },
8
- full: { type: 'string', pattern: '^(\\d+)$' },
9
- dir: { type: 'string', pattern: '^(\\d+)$' },
10
- },
11
- };
12
-
13
- async function plugin(fastify) {
14
- fastify.get('/logger-file/*', { config: { policy: ['site'] }, schema: loggerSchema }, loggerFile);
15
- }
16
-
17
- export default plugin;
1
+ import loggerFile from './controllers/logger.file.js';
2
+
3
+ // import loggerTest from './controllers/logger.test.api.js';
4
+
5
+ const loggerSchema = {
6
+ querystring: {
7
+ download: { type: 'string', pattern: '^(\\d+)$' },
8
+ full: { type: 'string', pattern: '^(\\d+)$' },
9
+ dir: { type: 'string', pattern: '^(\\d+)$' },
10
+ },
11
+ };
12
+
13
+ async function plugin(fastify) {
14
+ fastify.get('/logger-file/*', { config: { policy: ['site'] }, schema: loggerSchema }, loggerFile);
15
+ }
16
+
17
+ export default plugin;
@@ -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(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,156 +1,156 @@
1
- import {
2
- config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook,
3
- handlebars,
4
- } from '../../../../utils.js';
5
-
6
- const maxLimit = 100;
7
- export default async function dataAPI(req) {
8
- const {
9
- pg, params, query = {}, user = {},
10
- } = req;
11
-
12
- const time = Date.now();
13
-
14
- const { uid } = user;
15
-
16
- const hookData = await applyHook('preData', {
17
- table: params?.table, id: params?.id, user,
18
- });
19
- if (hookData?.message && hookData?.status) {
20
- return { message: hookData?.message, status: hookData?.status };
21
- }
22
-
23
- const loadTable = await getTemplate('table', hookData?.table || params.table);
24
- if (!loadTable) { return { message: 'template not found', status: 404 }; }
25
-
26
- const id = hookData?.id || params?.id;
27
- const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
28
-
29
- if (!actions.includes('view') && !config?.local) {
30
- return { message: 'access restricted', status: 403 };
31
- }
32
-
33
- const {
34
- table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
35
- } = loadTable;
36
-
37
- const tableMeta = await getMeta(table);
38
- if (tableMeta?.view) {
39
- if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
40
- Object.assign(tableMeta, { pk: loadTable?.key });
41
- }
42
- const { pk, columns: dbColumns = [] } = tableMeta || {};
43
-
44
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
45
-
46
- const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
47
- const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
48
- ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
49
- : '';
50
- const columnList = dbColumns.map((el) => el.name || el).join(',');
51
- 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('') || '';
52
- const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
53
- const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
54
-
55
- if (params.id && columnList.includes(params.id)) {
56
- return gisIRColumn({
57
- pg,
58
- layer: params.table,
59
- column: params.id,
60
- sql: query.sql,
61
- filter: query.filter,
62
- search: query.search,
63
- state: query.state,
64
- custom: query.custom,
65
- });
66
- }
67
-
68
- const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
69
- const fData = checkFilter ? await getFilterSQL({
70
- table: params.table,
71
- filter: query.filter,
72
- search: query.search,
73
- state: query.state,
74
- custom: query.custom,
75
- json: 1,
76
- }) : {};
77
-
78
- const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
79
-
80
- const limit = Math.min(maxLimit, +(query.limit || 20));
81
-
82
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
83
- // id, query, filter
84
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
85
-
86
- const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
87
- const search = loadTable.meta?.search && query.search
88
- ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%')}%'`).join(' or ')})`
89
- : null;
90
- const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
91
- const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
92
- const bbox = meta?.bbox && queryBbox.filter((el) => !Number.isNaN(el))?.length === 4 ? `${meta.bbox} && 'box(${queryBbox[0]} ${queryBbox[1]},${queryBbox[2]} ${queryBbox[3]})'::box2d ` : undefined;
93
-
94
- const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
95
- const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
96
-
97
- // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
98
- const q = `select ${pk ? `"${pk}" as id,` : ''}
99
- ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
100
- ${metaCols}
101
-
102
- ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
103
- from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
104
- ${sqlTable}
105
- ${cardSqlTable}
106
- where ${where.join(' and ') || 'true'}
107
- ${order} ${offset} limit ${limit}`
108
- .replace(/{{uid}}/g, uid);
109
-
110
- // if (user?.user_type === 'superadmin') console.log(q);
111
-
112
- if (query.sql === '1') { return q; }
113
-
114
- const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
115
-
116
- const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
117
-
118
- const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type));
119
- const qCount = `select
120
- count(*)::int as total,
121
- count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
122
- ${aggregates.length ? `,${aggregates.map((el) => `sum(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
123
- from ${table} t ${sqlTable}
124
- where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
125
- .replace(/{{uid}}/g, uid);
126
-
127
- if (query.sql === '2') { return qCount; }
128
-
129
- const counts = keyQuery || hookData?.id || params.id
130
- ? { total: rows.length, filtered: rows.length }
131
- : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
132
-
133
- const { total, filtered } = counts;
134
- const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
135
-
136
- await metaFormat({ rows, table: hookData?.table || params.table });
137
- const res = {
138
- time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, rows, meta, columns, filters,
139
- };
140
-
141
- // console.log({ add: loadTable.table, form: loadTable.form });
142
- if (uid && actions.includes('add')) {
143
- const addTokens = setToken({
144
- ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
145
- uid,
146
- array: 1,
147
- });
148
- Object.assign(res, { addToken: addTokens[0] });
149
- }
150
-
151
- const result = await applyHook('afterData', {
152
- table: loadTable.table, payload: res, user,
153
- });
154
-
155
- return result || res;
156
- }
1
+ import {
2
+ config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook,
3
+ handlebars,
4
+ } from '../../../../utils.js';
5
+
6
+ const maxLimit = 100;
7
+ export default async function dataAPI(req) {
8
+ const {
9
+ pg, params, query = {}, user = {},
10
+ } = req;
11
+
12
+ const time = Date.now();
13
+
14
+ const { uid } = user;
15
+
16
+ const hookData = await applyHook('preData', {
17
+ table: params?.table, id: params?.id, user,
18
+ });
19
+ if (hookData?.message && hookData?.status) {
20
+ return { message: hookData?.message, status: hookData?.status };
21
+ }
22
+
23
+ const loadTable = await getTemplate('table', hookData?.table || params.table);
24
+ if (!loadTable) { return { message: 'template not found', status: 404 }; }
25
+
26
+ const id = hookData?.id || params?.id;
27
+ const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
28
+
29
+ if (!actions.includes('view') && !config?.local) {
30
+ return { message: 'access restricted', status: 403 };
31
+ }
32
+
33
+ const {
34
+ table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
35
+ } = loadTable;
36
+
37
+ const tableMeta = await getMeta(table);
38
+ if (tableMeta?.view) {
39
+ if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
40
+ Object.assign(tableMeta, { pk: loadTable?.key });
41
+ }
42
+ const { pk, columns: dbColumns = [] } = tableMeta || {};
43
+
44
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
45
+
46
+ const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
47
+ const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
48
+ ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
49
+ : '';
50
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
51
+ 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('') || '';
52
+ const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
53
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
54
+
55
+ if (params.id && columnList.includes(params.id)) {
56
+ return gisIRColumn({
57
+ pg,
58
+ layer: params.table,
59
+ column: params.id,
60
+ sql: query.sql,
61
+ filter: query.filter,
62
+ search: query.search,
63
+ state: query.state,
64
+ custom: query.custom,
65
+ });
66
+ }
67
+
68
+ const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
69
+ const fData = checkFilter ? await getFilterSQL({
70
+ table: params.table,
71
+ filter: query.filter,
72
+ search: query.search,
73
+ state: query.state,
74
+ custom: query.custom,
75
+ json: 1,
76
+ }) : {};
77
+
78
+ const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
79
+
80
+ const limit = Math.min(maxLimit, +(query.limit || 20));
81
+
82
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
83
+ // id, query, filter
84
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
85
+
86
+ const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
87
+ const search = loadTable.meta?.search && query.search
88
+ ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%')}%'`).join(' or ')})`
89
+ : null;
90
+ const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
91
+ const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
92
+ const bbox = meta?.bbox && queryBbox.filter((el) => !Number.isNaN(el))?.length === 4 ? `${meta.bbox} && 'box(${queryBbox[0]} ${queryBbox[1]},${queryBbox[2]} ${queryBbox[3]})'::box2d ` : undefined;
93
+
94
+ const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
95
+ const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
96
+
97
+ // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
98
+ const q = `select ${pk ? `"${pk}" as id,` : ''}
99
+ ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
100
+ ${metaCols}
101
+
102
+ ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
103
+ from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
104
+ ${sqlTable}
105
+ ${cardSqlTable}
106
+ where ${where.join(' and ') || 'true'}
107
+ ${order} ${offset} limit ${limit}`
108
+ .replace(/{{uid}}/g, uid);
109
+
110
+ // if (user?.user_type === 'superadmin') console.log(q);
111
+
112
+ if (query.sql === '1') { return q; }
113
+
114
+ const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
115
+
116
+ const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
117
+
118
+ const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type));
119
+ const qCount = `select
120
+ count(*)::int as total,
121
+ count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
122
+ ${aggregates.length ? `,${aggregates.map((el) => `sum(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
123
+ from ${table} t ${sqlTable}
124
+ where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
125
+ .replace(/{{uid}}/g, uid);
126
+
127
+ if (query.sql === '2') { return qCount; }
128
+
129
+ const counts = keyQuery || hookData?.id || params.id
130
+ ? { total: rows.length, filtered: rows.length }
131
+ : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
132
+
133
+ const { total, filtered } = counts;
134
+ const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
135
+
136
+ await metaFormat({ rows, table: hookData?.table || params.table });
137
+ const res = {
138
+ time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, rows, meta, columns, filters,
139
+ };
140
+
141
+ // console.log({ add: loadTable.table, form: loadTable.form });
142
+ if (uid && actions.includes('add')) {
143
+ const addTokens = setToken({
144
+ ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
145
+ uid,
146
+ array: 1,
147
+ });
148
+ Object.assign(res, { addToken: addTokens[0] });
149
+ }
150
+
151
+ const result = await applyHook('afterData', {
152
+ table: loadTable.table, payload: res, user,
153
+ });
154
+
155
+ return result || res;
156
+ }