@opengis/fastify-table 1.1.49 → 1.1.51

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 (190) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/.gitlab-ci.yml +18 -0
  3. package/Changelog.md +352 -351
  4. package/cron/funcs/addCron.js +132 -132
  5. package/crud/controllers/deleteCrud.js +36 -31
  6. package/crud/controllers/insert.js +71 -70
  7. package/crud/controllers/update.js +76 -73
  8. package/crud/funcs/dataDelete.js +19 -19
  9. package/crud/funcs/dataInsert.js +30 -30
  10. package/crud/funcs/dataUpdate.js +48 -48
  11. package/crud/funcs/getAccess.js +46 -56
  12. package/crud/funcs/getOpt.js +10 -10
  13. package/crud/funcs/setOpt.js +16 -16
  14. package/crud/funcs/setToken.js +2 -2
  15. package/crud/funcs/utils/getFolder.js +9 -9
  16. package/crud/funcs/utils/logChanges.js +62 -62
  17. package/crud/index.js +36 -36
  18. package/docs/.vitepress/abbr.mjs +26 -26
  19. package/docs/.vitepress/config.mjs +127 -127
  20. package/docs/.vitepress/navigation.mjs +82 -82
  21. package/docs/.vitepress/theme/Layout.vue +17 -17
  22. package/docs/.vitepress/theme/components/NavigationLinks.vue +102 -102
  23. package/docs/.vitepress/theme/components/Panzoom.vue +169 -169
  24. package/docs/.vitepress/theme/index.mjs +15 -15
  25. package/docs/.vitepress/theme/style.scss +163 -163
  26. package/docs/abbr.json +4 -4
  27. package/docs/api/cron/cronApi.md +56 -56
  28. package/docs/api/crud/deleteCrud.md +58 -58
  29. package/docs/api/crud/insert.md +82 -82
  30. package/docs/api/crud/update.md +85 -85
  31. package/docs/api/index.md +47 -47
  32. package/docs/api/notification/testEmail.md +91 -91
  33. package/docs/api/table/card.md +73 -73
  34. package/docs/api/table/data.md +134 -134
  35. package/docs/api/table/export.md +60 -60
  36. package/docs/api/table/filter.md +104 -104
  37. package/docs/api/table/form.md +126 -126
  38. package/docs/api/table/search.md +123 -123
  39. package/docs/api/table/suggest.md +156 -156
  40. package/docs/api/table/table.md +107 -107
  41. package/docs/api/user/user.cls.id.md +77 -77
  42. package/docs/api/user/user.cls.md +49 -49
  43. package/docs/api/user/user.cls.post.md +62 -62
  44. package/docs/api/user/user.info.md +37 -37
  45. package/docs/api/utils/logger.file.md +60 -60
  46. package/docs/api/utils/next.id.md +34 -34
  47. package/docs/api/utils/properties.add.md +127 -127
  48. package/docs/api/utils/properties.get.md +73 -73
  49. package/docs/api/utils/status.monitor.md +36 -36
  50. package/docs/api/widget/widget.del.md +76 -76
  51. package/docs/api/widget/widget.get.md +233 -233
  52. package/docs/api/widget/widget.set.md +88 -88
  53. package/docs/db/admin.md +947 -947
  54. package/docs/db/crm.md +564 -564
  55. package/docs/db/index.md +9 -9
  56. package/docs/db/log.md +204 -204
  57. package/docs/hook/card/afterCard.md +20 -20
  58. package/docs/hook/card/preCard.md +25 -25
  59. package/docs/hook/data/afterData.md +26 -26
  60. package/docs/hook/data/preData.md +26 -26
  61. package/docs/hook/deleteCrud/afterDelete.md +21 -21
  62. package/docs/hook/deleteCrud/preDelete.md +26 -26
  63. package/docs/hook/form/afterForm.md +19 -19
  64. package/docs/hook/form/preForm.md +26 -26
  65. package/docs/hook/getTemplate/afterTemplate.md +24 -24
  66. package/docs/hook/getTemplate/preTemplate.md +29 -29
  67. package/docs/hook/index.md +45 -45
  68. package/docs/hook/insert/afterInsert.md +41 -41
  69. package/docs/hook/insert/preInsert.md +25 -25
  70. package/docs/hook/table/afterTable.md +20 -20
  71. package/docs/hook/table/preTable.md +25 -25
  72. package/docs/hook/update/afterUpdate.md +41 -41
  73. package/docs/hook/update/preUpdate.md +25 -25
  74. package/docs/index.md +42 -42
  75. package/docs/public/fastify-dark.svg +3 -3
  76. package/docs/public/logo-short-dark.svg +11 -11
  77. package/docs/public/logo-short.svg +10 -10
  78. package/docs/public/logo.svg +19 -19
  79. package/docs/readme/index.md +121 -121
  80. package/docs/templates/card.md +83 -83
  81. package/docs/templates/cls.md +29 -29
  82. package/docs/templates/filters.md +91 -91
  83. package/docs/templates/forms.md +139 -139
  84. package/docs/templates/index.md +28 -28
  85. package/docs/templates/select.md +90 -90
  86. package/docs/templates/table.md +162 -162
  87. package/docs/utils/cron/addCron.md +29 -29
  88. package/docs/utils/crud/dataInsert.md +51 -51
  89. package/docs/utils/crud/dataUpdate.md +52 -52
  90. package/docs/utils/crud/getOpt.md +33 -33
  91. package/docs/utils/crud/isFileExists.md +37 -37
  92. package/docs/utils/crud/setOpt.md +37 -37
  93. package/docs/utils/hook/addHook.md +74 -74
  94. package/docs/utils/hook/applyHook.md +64 -64
  95. package/docs/utils/index.md +47 -47
  96. package/docs/utils/notification/addNotification.md +28 -28
  97. package/docs/utils/notification/notification.md +41 -41
  98. package/docs/utils/pg/autoIndex.md +22 -22
  99. package/docs/utils/pg/getMeta.md +58 -58
  100. package/docs/utils/pg/getPG.md +34 -34
  101. package/docs/utils/pg/init.md +29 -29
  102. package/docs/utils/pg/pg.md +70 -70
  103. package/docs/utils/redis/getRedis.md +36 -36
  104. package/docs/utils/redis/rclient.md +74 -74
  105. package/docs/utils/table/getForm.md +68 -68
  106. package/docs/utils/table/getMeta.md +55 -55
  107. package/docs/utils/table/getSelect.md +38 -38
  108. package/docs/utils/table/getSelectMeta.md +46 -46
  109. package/docs/utils/table/getTable.md +77 -77
  110. package/helper.js +30 -30
  111. package/index.js +105 -105
  112. package/migration/exec.migrations.js +79 -79
  113. package/module/core/select/core.user_mentioned.sql +1 -1
  114. package/module/test/cls/itree.composition.json +25 -25
  115. package/module/test/table/test.rest_zone.table.json +265 -265
  116. package/notification/controllers/readNotifications.js +30 -30
  117. package/notification/controllers/testEmail.js +50 -50
  118. package/notification/controllers/userNotifications.js +64 -64
  119. package/notification/funcs/addNotification.js +21 -21
  120. package/notification/funcs/sendNotification.js +112 -112
  121. package/package.json +42 -41
  122. package/pg/funcs/getMeta.js +29 -29
  123. package/pg/funcs/getPG.js +30 -30
  124. package/pg/pgClients.js +20 -20
  125. package/policy/funcs/checkPolicy.js +92 -92
  126. package/policy/funcs/sqlInjection.js +33 -33
  127. package/policy/index.js +14 -14
  128. package/redis/client.js +8 -8
  129. package/redis/funcs/redisClients.js +2 -2
  130. package/redis/index.js +19 -19
  131. package/server/migrations/0.sql +78 -78
  132. package/server/migrations/cls.sql +39 -39
  133. package/server/migrations/properties.sql +144 -144
  134. package/server/migrations/roles.sql +172 -166
  135. package/server/migrations/users.sql +168 -168
  136. package/server.js +26 -26
  137. package/table/controllers/data.js +150 -134
  138. package/table/controllers/filter.js +50 -50
  139. package/table/controllers/form.js +42 -42
  140. package/table/controllers/search.js +80 -80
  141. package/table/controllers/suggest.js +79 -79
  142. package/table/controllers/table.js +83 -79
  143. package/table/controllers/utils/addTemplateDir.js +8 -8
  144. package/table/controllers/utils/getSelect.js +19 -19
  145. package/table/controllers/utils/getSelectMeta.js +66 -66
  146. package/table/controllers/utils/getTemplate_old.js +28 -28
  147. package/table/controllers/utils/getTemplates.js +18 -18
  148. package/table/controllers/utils/gisIRColumn.js +67 -67
  149. package/table/controllers/utils/loadTemplate.js +1 -1
  150. package/table/controllers/utils/loadTemplatePath.js +1 -1
  151. package/table/controllers/utils/userTemplateDir.js +1 -1
  152. package/table/funcs/getFilterSQL/index.js +94 -94
  153. package/table/funcs/getFilterSQL/util/formatValue.js +170 -170
  154. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  155. package/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  156. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  157. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  158. package/table/funcs/metaFormat/getSelectVal.js +21 -21
  159. package/table/funcs/metaFormat/index.js +28 -28
  160. package/table/index.js +37 -84
  161. package/table/schema.js +54 -0
  162. package/test/api/applyHook.test.js +95 -95
  163. package/test/api/crud.test.js +89 -89
  164. package/test/api/crud.xss.test.js +80 -80
  165. package/test/api/suggest.test.js +66 -66
  166. package/test/api/table.test.js +134 -134
  167. package/test/api/user.test.js +85 -85
  168. package/test/api/widget.test.js +117 -117
  169. package/test/helper/formatDate.test.js +62 -62
  170. package/test/templates/select/test.storage.data.json +3 -3
  171. package/test/templates/select/test.suggest.ato_new.json +3 -3
  172. package/test/templates/select/test.suggest.ato_new.sql +25 -25
  173. package/test/templates/select/test.suggest.data.json +4 -4
  174. package/test/templates/select/test.suggest.parent.sql +1 -1
  175. package/user/controllers/user.cls.id.js +14 -14
  176. package/user/controllers/user.cls.js +75 -75
  177. package/user/controllers/user.cls.post.js +55 -55
  178. package/user/controllers/user.info.js +21 -21
  179. package/util/controllers/logger.file.js +91 -91
  180. package/util/controllers/properties.add.js +60 -60
  181. package/util/controllers/status.monitor.js +8 -8
  182. package/util/controllers/utils/checkUserAccess.js +17 -17
  183. package/util/controllers/utils/getRootDir.js +25 -25
  184. package/utils.js +104 -104
  185. package/widget/controllers/utils/historyFormat.js +76 -76
  186. package/widget/controllers/utils/obj2db.js +13 -13
  187. package/widget/controllers/widget.del.js +44 -44
  188. package/widget/controllers/widget.get.js +102 -102
  189. package/widget/controllers/widget.set.js +79 -79
  190. package/widget/index.js +40 -40
@@ -1,79 +1,79 @@
1
- import getSelectMeta from './utils/getSelectMeta.js';
2
- import getPG from '../../pg/funcs/getPG.js';
3
- import config from '../../config.js';
4
- import getTemplate from './utils/getTemplate.js';
5
- // import getTableSql from '../funcs/getFilterSQL/util/getTableSql.js';
6
-
7
- const limit = 50;
8
- const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Cache-Control': 'no-cache' };
9
-
10
- export default async function suggest(req) {
11
- const { params, query, pg: pg1 } = req;
12
-
13
- const lang = query.lang || 'ua';
14
- const time = Date.now();
15
- const parent = query.parent || '';
16
-
17
- const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
18
- const selectName = query.sel || query.name || params.data;
19
- if (!selectName) return { headers, status: 400, message: 'name is required' };
20
-
21
- const body = await getTemplate('table', table);
22
- if (table && !pg1.pk[body?.table || table]) {
23
- return { headers, status: 400, message: 'param name is invalid: 1' };
24
- }
25
- const columnExists = body?.columns?.find((col) => col?.name === column);
26
- if (table && (!column || !columnExists)) {
27
- return { headers, status: 400, message: 'param name is invalid: 2' };
28
- }
29
-
30
- const meta = table && column
31
- ? {
32
- original: `with c(id,text) as (select row_number() over(), ${column} from ${body?.table || table} group by ${column} ) select * from c`,
33
- searchQuery: '("text" ilike $1 )',
34
- }
35
- : await getSelectMeta({ name: selectName, nocache: query?.nocache });
36
- const pg = meta?.db ? getPG(meta.db) : pg1;
37
- if (!meta) return { headers, status: 404, message: 'Not found query select ' };
38
- if (query.meta) return meta;
39
-
40
- const { arr, searchQuery } = meta;
41
-
42
- if (arr) {
43
- const lower = query.key?.toLowerCase();
44
- const data = query.key || query.val
45
- ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
46
- : arr;
47
- return {
48
- limit, count: data.length, mode: 'array', time: Date.now() - time, data,
49
- };
50
- }
51
-
52
- // search
53
- const search = query.key ? searchQuery : null;
54
-
55
- // val
56
- // const pk = meta.originalCols.split(',')[0];
57
- const val = query.val ? ` id=any('{${query.val.replace(/'/g, "''")}}')` : '';
58
-
59
- const sqlSuggest = `${meta.original.replace(/{{parent}}/gi, parent)} where ${[search, val, 'id is not null'].filter((el) => el).join(' and ') || 'true'} limit ${limit}`;
60
- if (query.sql) return sqlSuggest;
61
-
62
- // query
63
- const { rows: dataNew } = meta.searchColumn ? { rows: [] } : await pg.query(sqlSuggest, query.key ? [`${query.key}%`] : []);
64
- const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`%${query.key}%`] : []) : {};
65
- const ids = dataNew.map((el) => el.id);
66
- const data = dataNew.concat((dataNew1 || []).filter((el) => !ids?.includes(el.id)));
67
-
68
- const message = {
69
- time: Date.now() - time,
70
- count: data.length,
71
- total: meta.count - 0,
72
- mode: 'sql',
73
- db: meta.db,
74
- sql: config.local ? sqlSuggest : undefined,
75
- data,
76
- };
77
-
78
- return message;
79
- }
1
+ import getSelectMeta from './utils/getSelectMeta.js';
2
+ import getPG from '../../pg/funcs/getPG.js';
3
+ import config from '../../config.js';
4
+ import getTemplate from './utils/getTemplate.js';
5
+ // import getTableSql from '../funcs/getFilterSQL/util/getTableSql.js';
6
+
7
+ const limit = 50;
8
+ const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Cache-Control': 'no-cache' };
9
+
10
+ export default async function suggest(req) {
11
+ const { params, query, pg: pg1 } = req;
12
+
13
+ const lang = query.lang || 'ua';
14
+ const time = Date.now();
15
+ const parent = query.parent || '';
16
+
17
+ const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
18
+ const selectName = query.sel || query.name || params.data;
19
+ if (!selectName) return { headers, status: 400, message: 'name is required' };
20
+
21
+ const body = await getTemplate('table', table);
22
+ if (table && !pg1.pk[body?.table || table]) {
23
+ return { headers, status: 400, message: 'param name is invalid: 1' };
24
+ }
25
+ const columnExists = body?.columns?.find((col) => col?.name === column);
26
+ if (table && (!column || !columnExists)) {
27
+ return { headers, status: 400, message: 'param name is invalid: 2' };
28
+ }
29
+
30
+ const meta = table && column
31
+ ? {
32
+ original: `with c(id,text) as (select row_number() over(), ${column} from ${body?.table || table} group by ${column} ) select * from c`,
33
+ searchQuery: '("text" ilike $1 )',
34
+ }
35
+ : await getSelectMeta({ name: selectName, nocache: query?.nocache });
36
+ const pg = meta?.db ? getPG(meta.db) : pg1;
37
+ if (!meta) return { headers, status: 404, message: 'Not found query select ' };
38
+ if (query.meta) return meta;
39
+
40
+ const { arr, searchQuery } = meta;
41
+
42
+ if (arr) {
43
+ const lower = query.key?.toLowerCase();
44
+ const data = query.key || query.val
45
+ ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
46
+ : arr;
47
+ return {
48
+ limit, count: data.length, mode: 'array', time: Date.now() - time, data,
49
+ };
50
+ }
51
+
52
+ // search
53
+ const search = query.key ? searchQuery : null;
54
+
55
+ // val
56
+ // const pk = meta.originalCols.split(',')[0];
57
+ const val = query.val ? ` id=any('{${query.val.replace(/'/g, "''")}}')` : '';
58
+
59
+ const sqlSuggest = `${meta.original.replace(/{{parent}}/gi, parent)} where ${[search, val, 'id is not null'].filter((el) => el).join(' and ') || 'true'} limit ${limit}`;
60
+ if (query.sql) return sqlSuggest;
61
+
62
+ // query
63
+ const { rows: dataNew } = meta.searchColumn ? { rows: [] } : await pg.query(sqlSuggest, query.key ? [`${query.key}%`] : []);
64
+ const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`%${query.key}%`] : []) : {};
65
+ const ids = dataNew.map((el) => el.id);
66
+ const data = dataNew.concat((dataNew1 || []).filter((el) => !ids?.includes(el.id)));
67
+
68
+ const message = {
69
+ time: Date.now() - time,
70
+ count: data.length,
71
+ total: meta.count - 0,
72
+ mode: 'sql',
73
+ db: meta.db,
74
+ sql: config.local ? sqlSuggest : undefined,
75
+ data,
76
+ };
77
+
78
+ return message;
79
+ }
@@ -1,79 +1,83 @@
1
- import getTemplate from './utils/getTemplate.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import applyHook from '../../hook/funcs/applyHook.js';
4
- import getAccess from '../../crud/funcs/getAccess.js';
5
-
6
- export default async function tableAPI(req) {
7
- const {
8
- pg, params, user, query = {},
9
- } = req;
10
- const hookData = await applyHook('preTable', {
11
- table: params?.table, id: params?.id, user,
12
- });
13
-
14
- if (hookData?.message && hookData?.status) {
15
- return { message: hookData?.message, status: hookData?.status };
16
- }
17
-
18
- if (!params?.id && !hookData?.id) {
19
- return { message: 'not enough params', status: 400 };
20
- }
21
-
22
- const loadTable = await getTemplate('table', hookData?.table || params.table) || {};
23
- if (!loadTable) {
24
- if (!pg.pk?.[hookData?.table || params.table]) { return { message: 'not found', status: 404 }; }
25
- }
26
-
27
- const {
28
- actions = [], scope, my,
29
- } = await getAccess({
30
- table: hookData?.table || params.table,
31
- id: hookData?.id || params?.id,
32
- user,
33
- }) || {};
34
-
35
- if (!actions.includes('get') || (scope === 'my' && !my)) {
36
- return { message: 'access restricted', status: 403 };
37
- }
38
-
39
- const {
40
- table, /* columns, */ form,
41
- } = loadTable;
42
-
43
- const { pk, columns: dbColumns = [] } = await getMeta(table || hookData?.table || params.table);
44
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
45
-
46
- // const cols = columns.map((el) => el.name || el).join(',');
47
- const schema = await getTemplate('form', hookData?.form || form) || {};
48
- // skip DataTable from another table
49
- const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
50
- // skip non-existing columns
51
- const columnList = dbColumns.map((el) => el.name || el).join(',');
52
-
53
- const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${table || hookData?.table || params.table} limit 0`) : {};
54
- const cols = loadTable?.table
55
- ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
56
- : fields.map((el) => (el?.name?.includes('geom') ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
57
- const where = [`"${pk}" = $1`, loadTable.query].filter((el) => el);
58
- const geom = columnList.includes('geom') ? ',st_asgeojson(geom)::json as geom' : '';
59
- const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${table || hookData?.table || params.table} t where ${where.join(' and ') || 'true'} limit 1`;
60
-
61
- if (query?.sql === '1') return q;
62
-
63
- const { rows } = await pg.query(q, [hookData?.id || params.id]);
64
-
65
- if (extraKeys?.length) {
66
- await Promise.all(rows?.map(async (row) => {
67
- await Promise.all(extraKeys?.map(async (key) => {
68
- const { colModel, table: extraTable, parent_id: parentId } = schema[key];
69
- const { rows: extraRows } = await pg.query(`select ${parentId} as parent, ${colModel.map((col) => col.name).join(',')} from ${extraTable} a where ${parentId}=$1`, [row.id]);
70
- Object.assign(row, { [key]: extraRows });
71
- }));
72
- }));
73
- }
74
-
75
- const res = await applyHook('afterTable', {
76
- table: loadTable?.table, payload: rows, user,
77
- });
78
- return res || rows?.[0] || {};
79
- }
1
+ import setToken from '../../crud/funcs/setToken.js';
2
+ import getTemplate from './utils/getTemplate.js';
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+ import applyHook from '../../hook/funcs/applyHook.js';
5
+ import getAccess from '../../crud/funcs/getAccess.js';
6
+
7
+ export default async function tableAPI(req) {
8
+ const {
9
+ pg, params, user, query = {},
10
+ } = req;
11
+ const hookData = await applyHook('preTable', {
12
+ table: params?.table, id: params?.id, user,
13
+ });
14
+
15
+ if (hookData?.message && hookData?.status) {
16
+ return { message: hookData?.message, status: hookData?.status };
17
+ }
18
+
19
+ if (!params?.id && !hookData?.id) {
20
+ return { message: 'not enough params', status: 400 };
21
+ }
22
+ const tableName = hookData?.table || params.table;
23
+ const loadTable = await getTemplate('table', tableName) || {};
24
+ if (!loadTable || (pg.pk?.[tableName])) {
25
+ return { message: 'not found', status: 404 };
26
+ }
27
+
28
+ const { actions = [], query: accessQuery } = await getAccess({
29
+ table: hookData?.table || params.table,
30
+ id: hookData?.id || params?.id,
31
+ user,
32
+ }) || {};
33
+
34
+ if (!actions.includes('edit')) {
35
+ return { message: 'access restricted', status: 403 };
36
+ }
37
+
38
+ const { table, /* columns, */ form } = loadTable;
39
+
40
+ const { pk, columns: dbColumns = [] } = await getMeta(table || hookData?.table || params.table);
41
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
42
+
43
+ // const cols = columns.map((el) => el.name || el).join(',');
44
+ const schema = await getTemplate('form', hookData?.form || form) || {};
45
+ // skip DataTable from another table
46
+ const extraKeys = Object.keys(schema)?.filter((key) => schema[key]?.type === 'DataTable' && schema[key]?.table && schema[key]?.parent_id && schema[key]?.colModel?.length);
47
+ // skip non-existing columns
48
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
49
+
50
+ const { fields = [] } = !loadTable?.table ? await pg.query(`select * from ${table || hookData?.table || params.table} limit 0`) : {};
51
+ const cols = loadTable?.table
52
+ ? Object.keys(schema || {}).filter((col) => columnList.includes(col) && !extraKeys.includes(col))?.map((col) => (col?.includes('geom') ? `st_asgeojson(${col})::json as "${col}"` : `"${col}"`))?.join(',')
53
+ : fields.map((el) => (el?.name?.includes('geom') ? `st_asgeojson(${el.name})::json as "${el.name}"` : `"${el?.name}"`)).join(',');
54
+ const where = [`"${pk}" = $1`, loadTable.query, accessQuery].filter((el) => el);
55
+ const geom = columnList.includes('geom') ? ',st_asgeojson(geom)::json as geom' : '';
56
+ const q = `select "${pk}" as id, ${cols || '*'} ${geom} from ${table || hookData?.table || params.table} t where ${where.join(' and ') || 'true'} limit 1`;
57
+
58
+ if (query?.sql === '1') return q;
59
+
60
+ const data = await pg.query(q, [hookData?.id || params.id]).then(el => el.rows[0]);
61
+ if (!data) return { message: 'not found', status: 404 };
62
+
63
+ if (extraKeys?.length) {
64
+ await Promise.all(extraKeys?.map(async (key) => {
65
+ const { colModel, table: extraTable, parent_id: parentId } = schema[key];
66
+ const { rows: extraRows } = await pg.query(`select ${parentId} as parent, ${colModel.map((col) => col.name).join(',')} from ${extraTable} a where ${parentId}=$1`, [row.id]);
67
+ Object.assign(data, { [key]: extraRows });
68
+ }));
69
+ }
70
+ if (user.uid) {
71
+ const [token] = setToken({
72
+ ids: [JSON.stringify({ id: params?.id, table: params.table || loadTable.table, form: loadTable.form })],
73
+ mode: 'w',
74
+ uid: user.uid,
75
+ array: 1,
76
+ });
77
+ data.token = token;
78
+ }
79
+ const res = await applyHook('afterTable', {
80
+ table: loadTable?.table, payload: [data], user,
81
+ });
82
+ return res || data || {};
83
+ }
@@ -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,19 +1,19 @@
1
- import getTemplate from './getTemplate.js';
2
-
3
- const loadCls = {};
4
-
5
- export default async function getSelect(name) {
6
- if (loadCls[name]) return loadCls[name];
7
-
8
- const clsData = await getTemplate(['cls', 'select'], name);
9
- if (!clsData) { return null; }
10
-
11
- // console.log(clsData);
12
- if (clsData && Array.isArray(clsData)) {
13
- loadCls[name] = { arr: clsData };
14
- return loadCls[name];
15
- }
16
-
17
- loadCls[name] = clsData.sql ? clsData : { sql: clsData };
18
- return loadCls[name];
19
- }
1
+ import getTemplate from './getTemplate.js';
2
+
3
+ const loadCls = {};
4
+
5
+ export default async function getSelect(name) {
6
+ if (loadCls[name]) return loadCls[name];
7
+
8
+ const clsData = await getTemplate(['cls', 'select'], name);
9
+ if (!clsData) { return null; }
10
+
11
+ // console.log(clsData);
12
+ if (clsData && Array.isArray(clsData)) {
13
+ loadCls[name] = { arr: clsData };
14
+ return loadCls[name];
15
+ }
16
+
17
+ loadCls[name] = clsData.sql ? clsData : { sql: clsData };
18
+ return loadCls[name];
19
+ }
@@ -1,66 +1,66 @@
1
- // import pgClients from '../../../pg/pgClients.js';
2
- import getPG from '../../../pg/funcs/getPG.js';
3
-
4
- import getSelect from './getSelect.js';
5
-
6
- /*
7
- function getTable(table) {
8
- // eslint-disable-next-line class-methods-use-this
9
- const result = table.toLowerCase().replace(/[\n\r]+/g, ' ').split(' from ').filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
10
- .map((el) => el.split(/[ )]/)[0]);
11
- return result?.pop();
12
- } */
13
-
14
- const selectMeta = {};
15
-
16
- export default async function getSelectMeta({ name, pg: pg1, nocache }) {
17
- if (selectMeta[name] && !nocache) return selectMeta[name];
18
-
19
- const cls = await getSelect(name);
20
-
21
- if (!cls) return null;
22
- if (cls.arr) return cls;
23
- if (!cls.sql) return null;
24
-
25
- const pg = pg1 || getPG({ db: cls.db || 'client' });
26
- const { sql: original } = cls;
27
- const sql = `with c(id,text) as (${original} ) select * from c `;
28
-
29
- /*= == meta table === */
30
- const tableNew = original.toLowerCase().replace(/\n/g, ' ').split(' from ').filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
31
- .map((el) => el.split(/[ )]/)[0].replace(/[\r\n]+/g, ''));
32
-
33
- const dataOrigin = await pg.query(`${sql} limit 0`);
34
-
35
- const dataOrigin1 = await pg.query(`${original} limit 0`);
36
-
37
- // const table = getTable(original);
38
- const count = cls?.count ?? await pg.query(`select count(*) from (${original})q`).then((el) => el?.rows?.[0].count);
39
-
40
- // column name
41
- const cols = dataOrigin.fields.map((el) => el.name);
42
- const type = dataOrigin.fields.map((el) => pg.pgType?.[el.dataTypeID] || 'text');
43
-
44
- const searchColumn = cls?.searchColumn || (
45
- dataOrigin.fields.find((el) => el.name === 'search') ? 'search' : dataOrigin.fields[1].name);
46
-
47
- const searchQuery = `(${searchColumn.split(',').map((el) => `"${el}" ilike $1 `).join(' or ')})`;
48
-
49
- const data = {
50
-
51
- type: type.join(','),
52
- cols: cols.join(','),
53
- originalCols: dataOrigin1.fields.map((el) => el.name).join(','),
54
- db: cls.db,
55
- original: original?.includes('where') ? `select * from (${sql})q` : sql,
56
- sql,
57
- count,
58
- searchQuery,
59
- table: tableNew.join(','),
60
- time: new Date().toISOString(),
61
-
62
- };
63
-
64
- selectMeta[name] = data;
65
- return data;
66
- }
1
+ // import pgClients from '../../../pg/pgClients.js';
2
+ import getPG from '../../../pg/funcs/getPG.js';
3
+
4
+ import getSelect from './getSelect.js';
5
+
6
+ /*
7
+ function getTable(table) {
8
+ // eslint-disable-next-line class-methods-use-this
9
+ const result = table.toLowerCase().replace(/[\n\r]+/g, ' ').split(' from ').filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
10
+ .map((el) => el.split(/[ )]/)[0]);
11
+ return result?.pop();
12
+ } */
13
+
14
+ const selectMeta = {};
15
+
16
+ export default async function getSelectMeta({ name, pg: pg1, nocache }) {
17
+ if (selectMeta[name] && !nocache) return selectMeta[name];
18
+
19
+ const cls = await getSelect(name);
20
+
21
+ if (!cls) return null;
22
+ if (cls.arr) return cls;
23
+ if (!cls.sql) return null;
24
+
25
+ const pg = pg1 || getPG({ db: cls.db || 'client' });
26
+ const { sql: original } = cls;
27
+ const sql = `with c(id,text) as (${original} ) select * from c `;
28
+
29
+ /*= == meta table === */
30
+ const tableNew = original.toLowerCase().replace(/\n/g, ' ').split(' from ').filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
31
+ .map((el) => el.split(/[ )]/)[0].replace(/[\r\n]+/g, ''));
32
+
33
+ const dataOrigin = await pg.query(`${sql} limit 0`);
34
+
35
+ const dataOrigin1 = await pg.query(`${original} limit 0`);
36
+
37
+ // const table = getTable(original);
38
+ const count = cls?.count ?? await pg.query(`select count(*) from (${original})q`).then((el) => el?.rows?.[0].count);
39
+
40
+ // column name
41
+ const cols = dataOrigin.fields.map((el) => el.name);
42
+ const type = dataOrigin.fields.map((el) => pg.pgType?.[el.dataTypeID] || 'text');
43
+
44
+ const searchColumn = cls?.searchColumn || (
45
+ dataOrigin.fields.find((el) => el.name === 'search') ? 'search' : dataOrigin.fields[1].name);
46
+
47
+ const searchQuery = `(${searchColumn.split(',').map((el) => `"${el}" ilike $1 `).join(' or ')})`;
48
+
49
+ const data = {
50
+
51
+ type: type.join(','),
52
+ cols: cols.join(','),
53
+ originalCols: dataOrigin1.fields.map((el) => el.name).join(','),
54
+ db: cls.db,
55
+ original: original?.includes('where') ? `select * from (${sql})q` : sql,
56
+ sql,
57
+ count,
58
+ searchQuery,
59
+ table: tableNew.join(','),
60
+ time: new Date().toISOString(),
61
+
62
+ };
63
+
64
+ selectMeta[name] = data;
65
+ return data;
66
+ }
@@ -1,28 +1,28 @@
1
- import { readFile } from 'fs/promises';
2
- import fs from 'fs';
3
- import path from 'path';
4
- import config from '../../../config.js';
5
-
6
- const loadTemplate = {};
7
-
8
- export default async function getTemplateDir(type, name) {
9
- if (!type) return null;
10
- if (!name) return null;
11
-
12
- const cwd = process.cwd();
13
- const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
14
-
15
- if (!loadTemplate[type]) {
16
- const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
17
- loadTemplate[type] = typeList;
18
- }
19
-
20
- const fullname = loadTemplate[type].find((el) => path.parse(el).name === name);
21
- const ext = fullname ? path.extname(fullname)?.slice(1) : null;
22
- if (!ext) return null;
23
-
24
- const sql = loadTemplate[type].includes(`${name}.sql`) ? await readFile(path.join(typeDir, `${name}.sql`), 'utf-8') : null;
25
- const data = loadTemplate[type].includes(`${name}.json`) ? JSON.parse(await readFile(path.join(typeDir, `${name}.json`), 'utf-8')) : await readFile(path.join(typeDir, `${name}.${ext}`), 'utf-8');
26
- if (sql) return { sql };
27
- return data;
28
- }
1
+ import { readFile } from 'fs/promises';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import config from '../../../config.js';
5
+
6
+ const loadTemplate = {};
7
+
8
+ export default async function getTemplateDir(type, name) {
9
+ if (!type) return null;
10
+ if (!name) return null;
11
+
12
+ const cwd = process.cwd();
13
+ const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
14
+
15
+ if (!loadTemplate[type]) {
16
+ const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
17
+ loadTemplate[type] = typeList;
18
+ }
19
+
20
+ const fullname = loadTemplate[type].find((el) => path.parse(el).name === name);
21
+ const ext = fullname ? path.extname(fullname)?.slice(1) : null;
22
+ if (!ext) return null;
23
+
24
+ const sql = loadTemplate[type].includes(`${name}.sql`) ? await readFile(path.join(typeDir, `${name}.sql`), 'utf-8') : null;
25
+ const data = loadTemplate[type].includes(`${name}.json`) ? JSON.parse(await readFile(path.join(typeDir, `${name}.json`), 'utf-8')) : await readFile(path.join(typeDir, `${name}.${ext}`), 'utf-8');
26
+ if (sql) return { sql };
27
+ return data;
28
+ }
@@ -1,18 +1,18 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import config from '../../../config.js';
4
-
5
- const loadTemplate = {};
6
-
7
- export default async function getTemplateDir(type) {
8
- if (!type) return null;
9
-
10
- const cwd = process.cwd();
11
- const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
12
-
13
- if (!loadTemplate[type]) {
14
- const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
15
- loadTemplate[type] = typeList;
16
- }
17
- return loadTemplate[type];
18
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import config from '../../../config.js';
4
+
5
+ const loadTemplate = {};
6
+
7
+ export default async function getTemplateDir(type) {
8
+ if (!type) return null;
9
+
10
+ const cwd = process.cwd();
11
+ const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
12
+
13
+ if (!loadTemplate[type]) {
14
+ const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
15
+ loadTemplate[type] = typeList;
16
+ }
17
+ return loadTemplate[type];
18
+ }