@opengis/fastify-table 1.1.63 → 1.1.65

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 (73) hide show
  1. package/index.js +109 -109
  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/properties.sql +144 -144
  6. package/server/migrations/roles.sql +175 -175
  7. package/server/migrations/users.sql +168 -168
  8. package/server/plugins/cron/funcs/addCron.js +128 -128
  9. package/server/plugins/cron/index.js +6 -6
  10. package/server/plugins/crud/funcs/dataDelete.js +21 -21
  11. package/server/plugins/crud/funcs/dataInsert.js +33 -33
  12. package/server/plugins/crud/funcs/dataUpdate.js +50 -50
  13. package/server/plugins/crud/funcs/getAccess.js +48 -48
  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/migration/funcs/exec.migrations.js +79 -79
  22. package/server/plugins/migration/index.js +7 -7
  23. package/server/plugins/pg/funcs/getMeta.js +28 -28
  24. package/server/plugins/pg/funcs/getPG.js +30 -30
  25. package/server/plugins/pg/pgClients.js +21 -21
  26. package/server/plugins/policy/funcs/checkPolicy.js +92 -92
  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 +15 -15
  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 +170 -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 +19 -19
  40. package/server/plugins/table/funcs/getSelectMeta.js +57 -57
  41. package/server/plugins/table/funcs/getTemplates.js +19 -19
  42. package/server/plugins/table/funcs/gisIRColumn.js +72 -72
  43. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  44. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  45. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +23 -23
  46. package/server/plugins/table/funcs/metaFormat/index.js +30 -30
  47. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  48. package/server/plugins/table/index.js +13 -13
  49. package/server/plugins/util/funcs/eventStream.js +28 -28
  50. package/server/plugins/util/index.js +7 -7
  51. package/server/routes/cron/index.js +14 -14
  52. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  53. package/server/routes/crud/controllers/insert.js +74 -74
  54. package/server/routes/crud/controllers/table.js +86 -86
  55. package/server/routes/crud/controllers/update.js +77 -77
  56. package/server/routes/crud/index.js +21 -21
  57. package/server/routes/logger/controllers/logger.file.js +92 -92
  58. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  59. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  60. package/server/routes/logger/index.js +17 -17
  61. package/server/routes/properties/controllers/properties.add.js +55 -55
  62. package/server/routes/properties/controllers/properties.get.js +17 -17
  63. package/server/routes/properties/index.js +16 -16
  64. package/server/routes/table/controllers/data.js +142 -142
  65. package/server/routes/table/controllers/filter.js +60 -60
  66. package/server/routes/table/controllers/form.js +42 -42
  67. package/server/routes/table/controllers/search.js +74 -74
  68. package/server/routes/table/controllers/suggest.js +84 -84
  69. package/server/routes/table/index.js +28 -28
  70. package/server/routes/table/schema.js +64 -64
  71. package/server/routes/util/controllers/status.monitor.js +8 -8
  72. package/server/routes/util/index.js +11 -11
  73. package/utils.js +120 -120
@@ -1,30 +1,30 @@
1
- import getTemplate from '../getTemplate.js';
2
- import getSelectVal from './getSelectVal.js';
3
-
4
- // import { getTemplate, getSelectVal } from '../../../../../utils.js';
5
-
6
- export default async function metaFormat({ rows, table }) {
7
- const loadTable = await getTemplate('table', table);
8
- const selectCols = loadTable?.columns?.filter((e) => e.data);
9
- const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
10
- if (!selectCols?.length && !metaCls?.length) return rows;
11
-
12
- // cls & select format
13
-
14
- await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
15
- const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
16
- if (!values.length) return null;
17
-
18
- const cls = await getSelectVal({ name: attr.data, values });
19
- if (!cls) return null;
20
- rows.forEach(el => {
21
- const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
22
- if (!val) return;
23
- Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
24
- });
25
-
26
- return null;
27
- }));
28
-
29
- return rows;
30
- }
1
+ import getTemplate from '../getTemplate.js';
2
+ import getSelectVal from './getSelectVal.js';
3
+
4
+ // import { getTemplate, getSelectVal } from '../../../../../utils.js';
5
+
6
+ export default async function metaFormat({ rows, table }) {
7
+ const loadTable = await getTemplate('table', table);
8
+ const selectCols = loadTable?.columns?.filter((e) => e.data);
9
+ const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
10
+ if (!selectCols?.length && !metaCls?.length) return rows;
11
+
12
+ // cls & select format
13
+
14
+ await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
15
+ const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
16
+ if (!values.length) return null;
17
+
18
+ const cls = await getSelectVal({ name: attr.data, values });
19
+ if (!cls) return null;
20
+ rows.forEach(el => {
21
+ const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
22
+ if (!val) return;
23
+ Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
24
+ });
25
+
26
+ return null;
27
+ }));
28
+
29
+ return rows;
30
+ }
@@ -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, mode: 'w', 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) {
22
- return { message: 'access restricted', status: 403 };
23
- }
24
- const loadTemplate = await getTemplate('table', del);
25
-
26
- const { table } = loadTemplate || hookData || 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, mode: 'w', 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 || 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,74 +1,74 @@
1
- import {
2
- applyHook, getAccess, getTemplate, checkXSS, dataInsert, getToken, config,
3
- } from '../../../../utils.js';
4
-
5
- export default async function insert(req) {
6
- const {
7
- user, params = {}, body = {},
8
- } = req || {};
9
- if (!user) return { message: 'access restricted', status: 403 };
10
- const hookData = await applyHook('preInsert', { table: params?.table, user });
11
- if (hookData?.message && hookData?.status) {
12
- return { message: hookData?.message, status: hookData?.status };
13
- }
14
- const tokenData = await getToken({
15
- uid: user.uid, token: params.table, mode: 'a', json: 1,
16
- });
17
-
18
- const { form, table: add } = hookData || tokenData || (config.auth?.disable ? req.params : {});
19
-
20
- const { actions = [] } = await getAccess({ table: add, user }) || {};
21
-
22
- if (!actions.includes('add') && !config?.local) {
23
- return { message: 'access restricted', status: 403 };
24
- }
25
-
26
- if (!add) {
27
- return { message: 'table is required', status: 400 };
28
- }
29
-
30
- const loadTemplate = await getTemplate('table', add);
31
- const { table } = loadTemplate || hookData || req.params || {};
32
- if (!table) {
33
- return { message: 'table not found', status: 404 };
34
- }
35
-
36
- const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
37
-
38
- const xssCheck = checkXSS({ body, schema: formData?.schema || formData });
39
-
40
- if (xssCheck.error && formData?.xssCheck !== false) {
41
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
42
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
43
- }
44
-
45
- const uid = user?.uid;
46
- if (![add, table].filter((el) => el !== 'admin.users')?.length) {
47
- Object.assign(body, { uid, editor_id: uid });
48
- }
49
- const res = await dataInsert({
50
- table: loadTemplate?.table, data: body, uid,
51
- });
52
-
53
- // admin.custom_column
54
- await applyHook('afterInsert', {
55
- table, body, payload: res, user,
56
- });
57
- // form DataTable
58
- const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && body[key].length);
59
- if (extraKeys?.length) {
60
- res.extra = {};
61
- await Promise.all(extraKeys?.map(async (key) => {
62
- const objId = body[formData[key].parent_id] || req.body?.id;
63
- const extraRows = await Promise.all(body[key].map(async (row) => {
64
- const extraRes = await dataInsert({
65
- table: formData[key].table, data: { ...row, [formData[key].parent_id]: objId }, uid,
66
- });
67
- return extraRes?.rows?.[0];
68
- }));
69
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
70
- }));
71
- }
72
-
73
- return { rows: res.rows, extra: res.extra };
74
- }
1
+ import {
2
+ applyHook, getAccess, getTemplate, checkXSS, dataInsert, getToken, config,
3
+ } from '../../../../utils.js';
4
+
5
+ export default async function insert(req) {
6
+ const {
7
+ user, params = {}, body = {},
8
+ } = req || {};
9
+ if (!user) return { message: 'access restricted', status: 403 };
10
+ const hookData = await applyHook('preInsert', { table: params?.table, user });
11
+ if (hookData?.message && hookData?.status) {
12
+ return { message: hookData?.message, status: hookData?.status };
13
+ }
14
+ const tokenData = await getToken({
15
+ uid: user.uid, token: params.table, mode: 'a', json: 1,
16
+ });
17
+
18
+ const { form, table: add } = hookData || tokenData || (config.auth?.disable ? req.params : {});
19
+
20
+ const { actions = [] } = await getAccess({ table: add, user }) || {};
21
+
22
+ if (!actions.includes('add') && !config?.local && !tokenData) {
23
+ return { message: 'access restricted', status: 403 };
24
+ }
25
+
26
+ if (!add) {
27
+ return { message: 'table is required', status: 400 };
28
+ }
29
+
30
+ const loadTemplate = await getTemplate('table', add);
31
+ const { table } = loadTemplate || hookData || req.params || {};
32
+ if (!table) {
33
+ return { message: 'table not found', status: 404 };
34
+ }
35
+
36
+ const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
37
+
38
+ const xssCheck = checkXSS({ body, schema: formData?.schema || formData });
39
+
40
+ if (xssCheck.error && formData?.xssCheck !== false) {
41
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
42
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
43
+ }
44
+
45
+ const uid = user?.uid;
46
+ if (![add, table].filter((el) => el !== 'admin.users')?.length) {
47
+ Object.assign(body, { uid, editor_id: uid });
48
+ }
49
+ const res = await dataInsert({
50
+ table: loadTemplate?.table, data: body, uid,
51
+ });
52
+
53
+ // admin.custom_column
54
+ await applyHook('afterInsert', {
55
+ table, body, payload: res, user,
56
+ });
57
+ // form DataTable
58
+ const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && body[key].length);
59
+ if (extraKeys?.length) {
60
+ res.extra = {};
61
+ await Promise.all(extraKeys?.map(async (key) => {
62
+ const objId = body[formData[key].parent_id] || req.body?.id;
63
+ const extraRows = await Promise.all(body[key].map(async (row) => {
64
+ const extraRes = await dataInsert({
65
+ table: formData[key].table, data: { ...row, [formData[key].parent_id]: objId }, uid,
66
+ });
67
+ return extraRes?.rows?.[0];
68
+ }));
69
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
70
+ }));
71
+ }
72
+
73
+ return { rows: res.rows, extra: res.extra };
74
+ }
@@ -1,86 +1,86 @@
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 (!tableName && !id) {
32
- return { message: 'not enough params', status: 400 };
33
- }
34
-
35
- const { actions = [], query: accessQuery } = await getAccess({
36
- table: tableName,
37
- id,
38
- user,
39
- }) || {};
40
-
41
- if (!actions.includes('edit') && !config?.local) {
42
- return { message: 'access restricted', status: 403 };
43
- }
44
-
45
- const { pk, columns: dbColumns = [] } = await getMeta(tableName);
46
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
47
-
48
- // const cols = columns.map((el) => el.name || el).join(',');
49
- const schema = await getTemplate('form', hookData?.form || form) || {};
50
- // skip DataTable from another table
51
- const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
52
- // skip non-existing columns
53
- const columnList = dbColumns.map((el) => el.name || el).join(',');
54
-
55
- const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${tableName} limit 0`) : {};
56
- const cols = loadTable?.table
57
- ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
58
- : fields.map((el) => (el?.name?.includes('geom') ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
59
- const where = [`"${pk}" = $1`, loadTable.query, accessQuery].filter((el) => el);
60
- const geom = columnList.includes('geom') ? ',st_asgeojson(geom)::json as geom' : '';
61
- const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${tableName} t where ${where.join(' and ') || 'true'} limit 1`;
62
-
63
- if (query?.sql === '1') return q;
64
-
65
- const data = await pg.query(q, [id]).then(el => el.rows[0]);
66
- if (!data) return { message: 'not found', status: 404 };
67
-
68
- if (extraKeys?.length) {
69
- await Promise.all(extraKeys?.map(async (key) => {
70
- const { colModel, table: extraTable, parent_id: parentId } = schema[key];
71
- const { rows: extraRows } = await pg.query(`select ${parentId} as parent, ${colModel.map((col) => col.name).join(',')} from ${extraTable} a where ${parentId}=$1`, [hookData?.id || params?.id]);
72
- Object.assign(data, { [key]: extraRows });
73
- }));
74
- }
75
- if (user.uid) {
76
- data.token = tokenData?.table ? params.table : setToken({
77
- ids: [JSON.stringify({ id, table: tableName, form: loadTable.form })],
78
- uid: user.uid,
79
- array: 1,
80
- })[0];
81
- }
82
- const res = await applyHook('afterTable', {
83
- table: tableName, payload: [data], user,
84
- });
85
- return res || data || {};
86
- }
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 (!tableName && !id) {
32
+ return { message: 'not enough params', status: 400 };
33
+ }
34
+
35
+ const { actions = [], query: accessQuery } = await getAccess({
36
+ table: tableName,
37
+ id,
38
+ user,
39
+ }) || {};
40
+
41
+ if (!actions.includes('edit') && !config?.local && !tokenData) {
42
+ return { message: 'access restricted', status: 403 };
43
+ }
44
+
45
+ const { pk, columns: dbColumns = [] } = await getMeta(tableName);
46
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
47
+
48
+ // const cols = columns.map((el) => el.name || el).join(',');
49
+ const schema = await getTemplate('form', hookData?.form || form) || {};
50
+ // skip DataTable from another table
51
+ const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
52
+ // skip non-existing columns
53
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
54
+
55
+ const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${tableName} limit 0`) : {};
56
+ const cols = loadTable?.table
57
+ ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
58
+ : fields.map((el) => (el?.name?.includes('geom') ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
59
+ const where = [`"${pk}" = $1`, loadTable.query, accessQuery].filter((el) => el);
60
+ const geom = columnList.includes('geom') ? ',st_asgeojson(geom)::json as geom' : '';
61
+ const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${tableName} t where ${where.join(' and ') || 'true'} limit 1`;
62
+
63
+ if (query?.sql === '1') return q;
64
+
65
+ const data = await pg.query(q, [id]).then(el => el.rows[0]);
66
+ if (!data) return { message: 'not found', status: 404 };
67
+
68
+ if (extraKeys?.length) {
69
+ await Promise.all(extraKeys?.map(async (key) => {
70
+ const { colModel, table: extraTable, parent_id: parentId } = schema[key];
71
+ const { rows: extraRows } = await pg.query(`select ${parentId} as parent, ${colModel.map((col) => col.name).join(',')} from ${extraTable} a where ${parentId}=$1`, [hookData?.id || params?.id]);
72
+ Object.assign(data, { [key]: extraRows });
73
+ }));
74
+ }
75
+ if (user.uid) {
76
+ data.token = tokenData?.table ? params.table : setToken({
77
+ ids: [JSON.stringify({ id, table: tableName, form: loadTable.form })],
78
+ uid: user.uid,
79
+ array: 1,
80
+ })[0];
81
+ }
82
+ const res = await applyHook('afterTable', {
83
+ table: tableName, payload: [data], user,
84
+ });
85
+ return res || data || {};
86
+ }