@opengis/fastify-table 1.1.131 → 1.1.133

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 (71) 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 +33 -33
  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 -170
  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 +28 -28
  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 +83 -83
  53. package/server/routes/crud/controllers/table.js +91 -91
  54. package/server/routes/crud/controllers/update.js +91 -91
  55. package/server/routes/logger/controllers/logger.file.js +92 -92
  56. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  57. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  58. package/server/routes/logger/index.js +17 -17
  59. package/server/routes/properties/controllers/properties.add.js +55 -55
  60. package/server/routes/properties/controllers/properties.get.js +17 -17
  61. package/server/routes/properties/index.js +16 -16
  62. package/server/routes/table/controllers/data.js +156 -156
  63. package/server/routes/table/controllers/filter.js +66 -66
  64. package/server/routes/table/controllers/form.js +42 -42
  65. package/server/routes/table/controllers/search.js +74 -74
  66. package/server/routes/table/controllers/suggest.js +158 -122
  67. package/server/routes/table/index.js +29 -29
  68. package/server/routes/table/schema.js +64 -64
  69. package/server/routes/util/controllers/status.monitor.js +8 -8
  70. package/server/routes/util/index.js +11 -11
  71. package/utils.js +122 -122
@@ -1,45 +1,45 @@
1
- import { handlebars } from '@opengis/fastify-hb/utils.js';
2
-
3
- import getTemplate from '../getTemplate.js';
4
- import getSelectVal from './getSelectVal.js';
5
-
6
- export default async function metaFormat({
7
- rows, table, cls, sufix = true,
8
- }) {
9
- const loadTable = table ? await getTemplate('table', table) : {};
10
- const selectCols = Object.keys(cls || {}).map(key => ({ name: key, data: cls[key] })).concat(loadTable?.columns?.filter((e) => e.data) || []);
11
- const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
12
- const htmlCols = loadTable?.columns?.filter?.((e) => e.name && e.format === 'html' && e.html) || [];
13
- if (!selectCols?.length && !metaCls?.length && !htmlCols?.length) return rows;
14
-
15
- await Promise.all(htmlCols.map(async (attr) => {
16
- await Promise.all(rows.filter(row => row?.[attr.name])?.map(async (row) => {
17
- const html = await handlebars.compile(attr.html)(row);
18
- Object.assign(row, { [attr.name]: html?.replaceAll(/<[^>]*>/g, '')?.replace(/\n/g, '')?.trim() });
19
- }));
20
- }));
21
- // cls & select format
22
-
23
- await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
24
- const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => (typeof el === 'boolean' ? true : el));
25
- if (!values.length) return null;
26
-
27
- const clsValues = await getSelectVal({ name: attr.data, values });
28
- if (!clsValues) return null;
29
-
30
- rows.forEach(el => {
31
- const val = el[attr.name]?.map?.(c => clsValues[c.toString()] || clsValues[c] || c) || clsValues[el[attr.name]?.toString()] || clsValues[el[attr.name]] || el[attr.name];
32
- if (!val) return;
33
- if (!sufix) {
34
- Object.assign(el, { [attr.name]: val.text || val });
35
- }
36
- else {
37
- Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
38
- }
39
- });
40
-
41
- return null;
42
- }));
43
-
44
- return rows;
45
- }
1
+ import { handlebars } from '@opengis/fastify-hb/utils.js';
2
+
3
+ import getTemplate from '../getTemplate.js';
4
+ import getSelectVal from './getSelectVal.js';
5
+
6
+ export default async function metaFormat({
7
+ rows, table, cls, sufix = true,
8
+ }) {
9
+ const loadTable = table ? await getTemplate('table', table) : {};
10
+ const selectCols = Object.keys(cls || {}).map(key => ({ name: key, data: cls[key] })).concat(loadTable?.columns?.filter((e) => e.data) || []);
11
+ const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
12
+ const htmlCols = loadTable?.columns?.filter?.((e) => e.name && e.format === 'html' && e.html) || [];
13
+ if (!selectCols?.length && !metaCls?.length && !htmlCols?.length) return rows;
14
+
15
+ await Promise.all(htmlCols.map(async (attr) => {
16
+ await Promise.all(rows.filter(row => row?.[attr.name])?.map(async (row) => {
17
+ const html = await handlebars.compile(attr.html)(row);
18
+ Object.assign(row, { [attr.name]: html?.replaceAll(/<[^>]*>/g, '')?.replace(/\n/g, '')?.trim() });
19
+ }));
20
+ }));
21
+ // cls & select format
22
+
23
+ await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
24
+ const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => (typeof el === 'boolean' ? true : el));
25
+ if (!values.length) return null;
26
+
27
+ const clsValues = await getSelectVal({ name: attr.data, values });
28
+ if (!clsValues) return null;
29
+
30
+ rows.forEach(el => {
31
+ const val = el[attr.name]?.map?.(c => clsValues[c.toString()] || clsValues[c] || c) || clsValues[el[attr.name]?.toString()] || clsValues[el[attr.name]] || el[attr.name];
32
+ if (!val) return;
33
+ if (!sufix) {
34
+ Object.assign(el, { [attr.name]: val.text || val });
35
+ }
36
+ else {
37
+ Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
38
+ }
39
+ });
40
+
41
+ return null;
42
+ }));
43
+
44
+ return rows;
45
+ }
@@ -1 +1 @@
1
- export default [];
1
+ export default [];
@@ -1,13 +1,13 @@
1
- import metaFormat from './funcs/metaFormat/index.js';
2
- import getFilterSQL from './funcs/getFilterSQL/index.js';
3
- import getTemplate from './funcs/getTemplate.js';
4
- import getSelect from './funcs/getSelect.js';
5
-
6
- async function plugin(fastify) {
7
- // fastify.decorate('metaFormat', metaFormat);
8
- // fastify.decorate('getFilterSQL', getFilterSQL);
9
- // fastify.decorate('getTemplate', getTemplate);
10
- // fastify.decorate('getSelect', getSelect);
11
- }
12
-
13
- export default plugin;
1
+ import metaFormat from './funcs/metaFormat/index.js';
2
+ import getFilterSQL from './funcs/getFilterSQL/index.js';
3
+ import getTemplate from './funcs/getTemplate.js';
4
+ import getSelect from './funcs/getSelect.js';
5
+
6
+ async function plugin(fastify) {
7
+ // fastify.decorate('metaFormat', metaFormat);
8
+ // fastify.decorate('getFilterSQL', getFilterSQL);
9
+ // fastify.decorate('getTemplate', getTemplate);
10
+ // fastify.decorate('getSelect', getSelect);
11
+ }
12
+
13
+ export default plugin;
@@ -1,28 +1,28 @@
1
- /* eslint-disable no-param-reassign */
2
- export default function eventStream(res) {
3
- if (!res) return console.log;
4
- const time = Date.now();
5
-
6
- // eslint-disable-next-line no-underscore-dangle
7
- if (!res?._headerSent) {
8
- res.raw.writeHead(200, {
9
- 'Content-Type': 'text/event-stream; charset=utf-8',
10
- 'Cache-Control': 'no-cache',
11
- Connection: 'keep-alive',
12
- 'X-Accel-Buffering': 'no',
13
- });
14
- res.hijack();
15
- }
16
- let prev = time;
17
- function send(mes, finish) {
18
- const t1 = Date.now();
19
- res.raw.write(`data: ${finish ? 'finish' : ''} ${typeof mes === 'object' ? JSON.stringify(mes) : mes} ${t1 - prev}/${t1 - time}ms\n\n`);
20
- prev = t1;
21
- if (finish) {
22
- res.raw.write('data: finish');
23
- res.raw.end('');
24
- }
25
- }
26
-
27
- return send;
28
- }
1
+ /* eslint-disable no-param-reassign */
2
+ export default function eventStream(res) {
3
+ if (!res) return console.log;
4
+ const time = Date.now();
5
+
6
+ // eslint-disable-next-line no-underscore-dangle
7
+ if (!res?._headerSent) {
8
+ res.raw.writeHead(200, {
9
+ 'Content-Type': 'text/event-stream; charset=utf-8',
10
+ 'Cache-Control': 'no-cache',
11
+ Connection: 'keep-alive',
12
+ 'X-Accel-Buffering': 'no',
13
+ });
14
+ res.hijack();
15
+ }
16
+ let prev = time;
17
+ function send(mes, finish) {
18
+ const t1 = Date.now();
19
+ res.raw.write(`data: ${finish ? 'finish' : ''} ${typeof mes === 'object' ? JSON.stringify(mes) : mes} ${t1 - prev}/${t1 - time}ms\n\n`);
20
+ prev = t1;
21
+ if (finish) {
22
+ res.raw.write('data: finish');
23
+ res.raw.end('');
24
+ }
25
+ }
26
+
27
+ return send;
28
+ }
@@ -1,7 +1,7 @@
1
- import eventStream from './funcs/eventStream.js';
2
-
3
- async function plugin(fastify) {
4
- // fastify.decorate('eventStream', eventStream);
5
- }
6
-
7
- export default plugin;
1
+ import eventStream from './funcs/eventStream.js';
2
+
3
+ async function plugin(fastify) {
4
+ // fastify.decorate('eventStream', eventStream);
5
+ }
6
+
7
+ export default plugin;
@@ -1,14 +1,14 @@
1
- import cronApi from './controllers/cronApi.js';
2
-
3
- const cronSchema = {
4
- params: {
5
- name: { type: 'string', pattern: '^([\\d\\w._-]+)$' },
6
- },
7
- };
8
-
9
- async function plugin(fastify, config = {}) {
10
- const prefix = config.prefix || '/api';
11
- fastify.get(`${prefix}/cron/:name`, { schema: cronSchema }, cronApi);
12
- }
13
-
14
- export default plugin;
1
+ import cronApi from './controllers/cronApi.js';
2
+
3
+ const cronSchema = {
4
+ params: {
5
+ name: { type: 'string', pattern: '^([\\d\\w._-]+)$' },
6
+ },
7
+ };
8
+
9
+ async function plugin(fastify, config = {}) {
10
+ const prefix = config.prefix || '/api';
11
+ fastify.get(`${prefix}/cron/:name`, { schema: cronSchema }, cronApi);
12
+ }
13
+
14
+ export default plugin;
@@ -1,36 +1,36 @@
1
- import {
2
- dataDelete, getTemplate, getAccess, applyHook, getToken, config,
3
- } from '../../../../utils.js';
4
-
5
- export default async function deleteCrud(req) {
6
- const { user, params = {} } = req || {};
7
- const hookData = await applyHook('preDelete', {
8
- table: params?.table, id: params?.id, user,
9
- });
10
- if (hookData?.message && hookData?.status) {
11
- return { message: hookData?.message, status: hookData?.status };
12
- }
13
-
14
- const tokenData = await getToken({
15
- uid: user.uid, token: params.table, json: 1,
16
- });
17
-
18
- const { table: del, id } = hookData || tokenData || (config.auth?.disable ? req.params : {});
19
- const { actions = [] } = await getAccess({ table: del, id, user }) || {};
20
-
21
- if (!actions.includes('del') && !config?.local && !tokenData) {
22
- return { message: 'access restricted', status: 403 };
23
- }
24
- const loadTemplate = await getTemplate('table', del);
25
-
26
- const { table } = loadTemplate || hookData || tokenData || req.params || {};
27
-
28
- if (!table) return { status: 404, message: 'table is required' };
29
- if (!id) return { status: 404, message: 'id is required' };
30
-
31
- const data = await dataDelete({
32
- table, id, uid: user?.uid,
33
- });
34
-
35
- return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
36
- }
1
+ import {
2
+ dataDelete, getTemplate, getAccess, applyHook, getToken, config,
3
+ } from '../../../../utils.js';
4
+
5
+ export default async function deleteCrud(req) {
6
+ const { user, params = {} } = req || {};
7
+ const hookData = await applyHook('preDelete', {
8
+ table: params?.table, id: params?.id, user,
9
+ });
10
+ if (hookData?.message && hookData?.status) {
11
+ return { message: hookData?.message, status: hookData?.status };
12
+ }
13
+
14
+ const tokenData = await getToken({
15
+ uid: user.uid, token: params.table, json: 1,
16
+ });
17
+
18
+ const { table: del, id } = hookData || tokenData || (config.auth?.disable ? req.params : {});
19
+ const { actions = [] } = await getAccess({ table: del, id, user }) || {};
20
+
21
+ if (!actions.includes('del') && !config?.local && !tokenData) {
22
+ return { message: 'access restricted', status: 403 };
23
+ }
24
+ const loadTemplate = await getTemplate('table', del);
25
+
26
+ const { table } = loadTemplate || hookData || tokenData || req.params || {};
27
+
28
+ if (!table) return { status: 404, message: 'table is required' };
29
+ if (!id) return { status: 404, message: 'id is required' };
30
+
31
+ const data = await dataDelete({
32
+ table, id, uid: user?.uid,
33
+ });
34
+
35
+ return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
36
+ }
@@ -1,83 +1,83 @@
1
- import {
2
- applyHook, getAccess, getTemplate, checkXSS, dataInsert, getToken, config,
3
- pgClients,
4
- } from '../../../../utils.js';
5
-
6
- export default async function insert(req) {
7
- const {
8
- user = {}, params = {}, body = {},
9
- } = req || {};
10
- if (!user) return { message: 'access restricted', status: 403 };
11
- const hookData = await applyHook('preInsert', { table: params?.table, user });
12
- if (hookData?.message && hookData?.status) {
13
- return { message: hookData?.message, status: hookData?.status };
14
- }
15
- const tokenData = await getToken({
16
- uid: user?.uid, token: params.table, mode: 'a', json: 1,
17
- });
18
-
19
- const { form, table: add } = hookData || tokenData || (config.auth?.disable ? req.params : {});
20
-
21
- const { actions = [] } = await getAccess({ table: add, user }) || {};
22
-
23
- if (!actions.includes('add') && !config?.local && !tokenData) {
24
- return { message: 'access restricted', status: 403 };
25
- }
26
-
27
- if (!add) {
28
- return { message: 'table is required', status: 400 };
29
- }
30
-
31
- const loadTemplate = await getTemplate('table', add);
32
- const { table } = loadTemplate || hookData || tokenData || req.params || {};
33
- if (!table) {
34
- return { message: 'table not found', status: 404 };
35
- }
36
-
37
- const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
38
- const schema = formData?.schema || formData;
39
-
40
- const xssCheck = checkXSS({ body, schema });
41
-
42
- if (xssCheck.error && formData?.xssCheck !== false) {
43
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
44
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
45
- }
46
-
47
- if (![add, table].includes('admin.users')) {
48
- Object.assign(body, { uid: user?.uid, editor_id: user?.uid });
49
- }
50
- if (tokenData?.obj) {
51
- const objData = tokenData.obj?.split('#').reduce((p, el) => ({ ...p, [el.split('=')[0]]: el.split('=')[1] }), {}) || {};
52
- Object.assign(body, objData);
53
- }
54
-
55
- const res = await dataInsert({
56
- id: params?.id, table: loadTemplate?.table || table, data: body, uid: user?.uid,
57
- });
58
- if (!res) return { message: 'nothing added ' };
59
-
60
- // admin.custom_column
61
- await applyHook('afterInsert', {
62
- table, token: params?.table, body, payload: res, user,
63
- });
64
- // form DataTable
65
- const extraKeys = Object.keys(schema || {})?.filter((key) => schema?.[key]?.type === 'DataTable' && schema?.[key]?.table && schema?.[key]?.parent_id && body[key]?.length);
66
-
67
- if (extraKeys?.length) {
68
- res.extra = {};
69
- await Promise.all(extraKeys?.map(async (key) => {
70
- const objId = body[schema[key].parent_id] || req.body?.id || res?.rows?.[0]?.[schema[key].parent_id];
71
- const extraRows = await Promise.all(body[key].map(async (row) => {
72
- const extraRes = await dataInsert({
73
- table: schema[key].table, data: { ...row, [schema[key].parent_id]: objId }, uid: user?.uid,
74
- });
75
- return extraRes?.rows?.[0];
76
- }));
77
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
78
- }));
79
- }
80
-
81
- const pk = pgClients.client?.pk?.[loadTemplate?.table || table];
82
- return { id: res?.rows?.[0]?.[pk], rows: res.rows, extra: res.extra };
83
- }
1
+ import {
2
+ applyHook, getAccess, getTemplate, checkXSS, dataInsert, getToken, config,
3
+ pgClients,
4
+ } from '../../../../utils.js';
5
+
6
+ export default async function insert(req) {
7
+ const {
8
+ user = {}, params = {}, body = {},
9
+ } = req || {};
10
+ if (!user) return { message: 'access restricted', status: 403 };
11
+ const hookData = await applyHook('preInsert', { table: params?.table, user });
12
+ if (hookData?.message && hookData?.status) {
13
+ return { message: hookData?.message, status: hookData?.status };
14
+ }
15
+ const tokenData = await getToken({
16
+ uid: user?.uid, token: params.table, mode: 'a', json: 1,
17
+ });
18
+
19
+ const { form, table: add } = hookData || tokenData || (config.auth?.disable ? req.params : {});
20
+
21
+ const { actions = [] } = await getAccess({ table: add, user }) || {};
22
+
23
+ if (!actions.includes('add') && !config?.local && !tokenData) {
24
+ return { message: 'access restricted', status: 403 };
25
+ }
26
+
27
+ if (!add) {
28
+ return { message: 'table is required', status: 400 };
29
+ }
30
+
31
+ const loadTemplate = await getTemplate('table', add);
32
+ const { table } = loadTemplate || hookData || tokenData || req.params || {};
33
+ if (!table) {
34
+ return { message: 'table not found', status: 404 };
35
+ }
36
+
37
+ const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
38
+ const schema = formData?.schema || formData;
39
+
40
+ const xssCheck = checkXSS({ body, schema });
41
+
42
+ if (xssCheck.error && formData?.xssCheck !== false) {
43
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
44
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
45
+ }
46
+
47
+ if (![add, table].includes('admin.users')) {
48
+ Object.assign(body, { uid: user?.uid, editor_id: user?.uid });
49
+ }
50
+ if (tokenData?.obj) {
51
+ const objData = tokenData.obj?.split('#').reduce((p, el) => ({ ...p, [el.split('=')[0]]: el.split('=')[1] }), {}) || {};
52
+ Object.assign(body, objData);
53
+ }
54
+
55
+ const res = await dataInsert({
56
+ id: params?.id, table: loadTemplate?.table || table, data: body, uid: user?.uid,
57
+ });
58
+ if (!res) return { message: 'nothing added ' };
59
+
60
+ // admin.custom_column
61
+ await applyHook('afterInsert', {
62
+ table, token: params?.table, body, payload: res, user,
63
+ });
64
+ // form DataTable
65
+ const extraKeys = Object.keys(schema || {})?.filter((key) => schema?.[key]?.type === 'DataTable' && schema?.[key]?.table && schema?.[key]?.parent_id && body[key]?.length);
66
+
67
+ if (extraKeys?.length) {
68
+ res.extra = {};
69
+ await Promise.all(extraKeys?.map(async (key) => {
70
+ const objId = body[schema[key].parent_id] || req.body?.id || res?.rows?.[0]?.[schema[key].parent_id];
71
+ const extraRows = await Promise.all(body[key].map(async (row) => {
72
+ const extraRes = await dataInsert({
73
+ table: schema[key].table, data: { ...row, [schema[key].parent_id]: objId }, uid: user?.uid,
74
+ });
75
+ return extraRes?.rows?.[0];
76
+ }));
77
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
78
+ }));
79
+ }
80
+
81
+ const pk = pgClients.client?.pk?.[loadTemplate?.table || table];
82
+ return { id: res?.rows?.[0]?.[pk], rows: res.rows, extra: res.extra };
83
+ }
@@ -1,91 +1,91 @@
1
- import {
2
- config, getAccess, getTemplate, getMeta, setToken, applyHook, getToken,
3
- } from '../../../../utils.js';
4
-
5
- export default async function tableAPI(req) {
6
- const {
7
- pg, params, user = {}, query = {},
8
- } = req;
9
- const tokenData = await getToken({ token: params?.table, uid: user.uid, json: 1 }) || {};
10
-
11
- const hookData = await applyHook('preTable', {
12
- table: params?.table, id: params?.id, ...tokenData || {}, user,
13
- });
14
-
15
- if (hookData?.message && hookData?.status) {
16
- return { message: hookData?.message, status: hookData?.status };
17
- }
18
- const tableName1 = hookData?.table || tokenData.table || params.table;
19
-
20
- const loadTable = await getTemplate('table', tableName1) || {};
21
- if (!loadTable && !pg.pk?.[tokenData.table]) {
22
- return { message: 'not found', status: 404 };
23
- }
24
-
25
- const { table, /* columns, */ form } = loadTable;
26
-
27
- const tableName = table || hookData?.table || tokenData.table || params.table;
28
-
29
- const id = hookData?.id || tokenData.id || params.id;
30
-
31
- if (tokenData && !id) return { message: {} };
32
- if (!tableName && !id) {
33
- return { message: 'not enough params', status: 400 };
34
- }
35
-
36
- const { actions = [], query: accessQuery } = await getAccess({
37
- table: hookData?.table || tokenData.table || params.table,
38
- id,
39
- user,
40
- }) || {};
41
-
42
- if (!actions.includes('edit') && !config?.local && !tokenData) {
43
- return { message: 'access restricted', status: 403 };
44
- }
45
-
46
- const { pk, columns: dbColumns = [] } = await getMeta(tableName);
47
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
48
-
49
- // const cols = columns.map((el) => el.name || el).join(',');
50
- const formName = hookData?.form || tokenData?.form || form;
51
- const formData = await getTemplate('form', formName) || {};
52
- const schema = formData?.schema || formData;
53
- // skip DataTable from another table
54
- const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
55
- // skip non-existing columns
56
- const columnList = dbColumns.map((el) => el.name || el).join(',');
57
-
58
- const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${tableName} limit 0`) : {};
59
- const cols = loadTable?.table
60
- ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') && schema?.[col]?.type === 'Geom' ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
61
- : fields.map((el) => (el?.name?.includes('geom') && pg.pgType[el?.dataTypeID] === 'geometry' ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
62
- const where = [`"${pk}" = $1`, loadTable.query, accessQuery].filter((el) => el);
63
- const geom = dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : '';
64
- const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${tableName} t where ${where.join(' and ') || 'true'} limit 1`;
65
-
66
- if (query?.sql === '1') return q;
67
-
68
- const data = await pg.query(q, [id]).then(el => el.rows[0]);
69
- if (!data) return { message: 'not found', status: 404 };
70
-
71
- if (extraKeys?.length) {
72
- await Promise.all(extraKeys?.map(async (key) => {
73
- const { colModel, table: extraTable, parent_id: parentId } = schema[key];
74
- const q1 = `select ${parentId} as parent, ${colModel.map((col) => col.name || col.key).join(',')} from ${extraTable} a where ${parentId}=$1`;
75
- // console.log(tableName, formName, q1);
76
- const { rows: extraRows } = await pg.query(q1, [hookData?.id || tokenData?.id || params?.id]);
77
- Object.assign(data, { [key]: extraRows });
78
- }));
79
- }
80
- if (user?.uid && actions?.includes?.('edit')) {
81
- data.token = tokenData?.table ? params.table : setToken({
82
- ids: [JSON.stringify({ id, table: tableName, form: loadTable.form })],
83
- uid: user.uid,
84
- array: 1,
85
- })[0];
86
- }
87
- const res = await applyHook('afterTable', {
88
- table: tableName, payload: [data], user,
89
- });
90
- return res || data || {};
91
- }
1
+ import {
2
+ config, getAccess, getTemplate, getMeta, setToken, applyHook, getToken,
3
+ } from '../../../../utils.js';
4
+
5
+ export default async function tableAPI(req) {
6
+ const {
7
+ pg, params, user = {}, query = {},
8
+ } = req;
9
+ const tokenData = await getToken({ token: params?.table, uid: user.uid, json: 1 }) || {};
10
+
11
+ const hookData = await applyHook('preTable', {
12
+ table: params?.table, id: params?.id, ...tokenData || {}, user,
13
+ });
14
+
15
+ if (hookData?.message && hookData?.status) {
16
+ return { message: hookData?.message, status: hookData?.status };
17
+ }
18
+ const tableName1 = hookData?.table || tokenData.table || params.table;
19
+
20
+ const loadTable = await getTemplate('table', tableName1) || {};
21
+ if (!loadTable && !pg.pk?.[tokenData.table]) {
22
+ return { message: 'not found', status: 404 };
23
+ }
24
+
25
+ const { table, /* columns, */ form } = loadTable;
26
+
27
+ const tableName = table || hookData?.table || tokenData.table || params.table;
28
+
29
+ const id = hookData?.id || tokenData.id || params.id;
30
+
31
+ if (tokenData && !id) return { message: {} };
32
+ if (!tableName && !id) {
33
+ return { message: 'not enough params', status: 400 };
34
+ }
35
+
36
+ const { actions = [], query: accessQuery } = await getAccess({
37
+ table: hookData?.table || tokenData.table || params.table,
38
+ id,
39
+ user,
40
+ }) || {};
41
+
42
+ if (!actions.includes('edit') && !config?.local && !tokenData) {
43
+ return { message: 'access restricted', status: 403 };
44
+ }
45
+
46
+ const { pk, columns: dbColumns = [] } = await getMeta(tableName);
47
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
48
+
49
+ // const cols = columns.map((el) => el.name || el).join(',');
50
+ const formName = hookData?.form || tokenData?.form || form;
51
+ const formData = await getTemplate('form', formName) || {};
52
+ const schema = formData?.schema || formData;
53
+ // skip DataTable from another table
54
+ const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
55
+ // skip non-existing columns
56
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
57
+
58
+ const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${tableName} limit 0`) : {};
59
+ const cols = loadTable?.table
60
+ ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') && schema?.[col]?.type === 'Geom' ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
61
+ : fields.map((el) => (el?.name?.includes('geom') && pg.pgType[el?.dataTypeID] === 'geometry' ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
62
+ const where = [`"${pk}" = $1`, loadTable.query, accessQuery].filter((el) => el);
63
+ const geom = dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : '';
64
+ const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${tableName} t where ${where.join(' and ') || 'true'} limit 1`;
65
+
66
+ if (query?.sql === '1') return q;
67
+
68
+ const data = await pg.query(q, [id]).then(el => el.rows[0]);
69
+ if (!data) return { message: 'not found', status: 404 };
70
+
71
+ if (extraKeys?.length) {
72
+ await Promise.all(extraKeys?.map(async (key) => {
73
+ const { colModel, table: extraTable, parent_id: parentId } = schema[key];
74
+ const q1 = `select ${parentId} as parent, ${colModel.map((col) => col.name || col.key).join(',')} from ${extraTable} a where ${parentId}=$1`;
75
+ // console.log(tableName, formName, q1);
76
+ const { rows: extraRows } = await pg.query(q1, [hookData?.id || tokenData?.id || params?.id]);
77
+ Object.assign(data, { [key]: extraRows });
78
+ }));
79
+ }
80
+ if (user?.uid && actions?.includes?.('edit')) {
81
+ data.token = tokenData?.table ? params.table : setToken({
82
+ ids: [JSON.stringify({ id, table: tableName, form: loadTable.form })],
83
+ uid: user.uid,
84
+ array: 1,
85
+ })[0];
86
+ }
87
+ const res = await applyHook('afterTable', {
88
+ table: tableName, payload: [data], user,
89
+ });
90
+ return res || data || {};
91
+ }