@opengis/fastify-table 1.2.16 → 1.2.18

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 (68) hide show
  1. package/README.md +86 -86
  2. package/index.js +79 -79
  3. package/package.json +1 -1
  4. package/server/migrations/0.sql +84 -84
  5. package/server/migrations/cls.sql +39 -39
  6. package/server/migrations/properties.sql +184 -184
  7. package/server/migrations/template.sql +34 -34
  8. package/server/migrations/users.sql +175 -175
  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 +24 -24
  12. package/server/plugins/crud/funcs/dataInsert.js +53 -53
  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 +118 -118
  19. package/server/plugins/crud/funcs/validateData.js +2 -2
  20. package/server/plugins/crud/index.js +23 -23
  21. package/server/plugins/hook/index.js +8 -8
  22. package/server/plugins/logger/errorStatus.js +19 -19
  23. package/server/plugins/logger/index.js +21 -21
  24. package/server/plugins/migration/exec.migrations.js +37 -37
  25. package/server/plugins/migration/index.js +7 -7
  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 +179 -179
  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/getTemplates.js +19 -19
  40. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  41. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  42. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  43. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +50 -50
  44. package/server/plugins/table/funcs/metaFormat/index.js +45 -45
  45. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  46. package/server/plugins/table/index.js +13 -13
  47. package/server/plugins/util/index.js +7 -7
  48. package/server/routes/cron/index.js +14 -14
  49. package/server/routes/crud/controllers/deleteCrud.js +39 -39
  50. package/server/routes/crud/controllers/table.js +91 -91
  51. package/server/routes/logger/controllers/logger.file.js +92 -92
  52. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  53. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  54. package/server/routes/logger/index.js +17 -17
  55. package/server/routes/properties/controllers/properties.add.js +55 -55
  56. package/server/routes/properties/controllers/properties.get.js +17 -17
  57. package/server/routes/properties/index.js +16 -16
  58. package/server/routes/table/controllers/data.js +98 -2
  59. package/server/routes/table/controllers/filter.js +67 -67
  60. package/server/routes/table/controllers/form.js +42 -42
  61. package/server/routes/table/controllers/search.js +74 -74
  62. package/server/routes/table/controllers/suggest.js +166 -166
  63. package/server/routes/table/controllers/utils/conditions.js +21 -0
  64. package/server/routes/table/index.js +29 -29
  65. package/server/routes/table/schema.js +64 -64
  66. package/server/routes/util/controllers/status.monitor.js +8 -8
  67. package/server/routes/util/index.js +11 -11
  68. package/utils.js +129 -129
@@ -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,7 +1,14 @@
1
1
  import {
2
- config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, getSelect,
2
+ config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, handlebarsSync, getSelect, setOpt,
3
3
  } from '../../../../utils.js';
4
4
 
5
+ import conditions from './utils/conditions.js';
6
+
7
+ const components = {
8
+ 'vs-widget-file': `select 'vs-widget-file' as component, count(*) from crm.files where entity_id=$1 and file_status<>3`,
9
+ 'vs-widget-comments': `select 'vs-widget-comments' as component, count(*) from crm.communications where entity_id=$1`
10
+ };
11
+
5
12
  const maxLimit = 100;
6
13
  export default async function dataAPI(req) {
7
14
  const {
@@ -150,8 +157,97 @@ export default async function dataAPI(req) {
150
157
  ?.forEach(el => status.push({ ...el, count: rows.filter(row => el.id === row[statusColumn.name]).length }));
151
158
  }
152
159
 
160
+ const template = await getTemplate('card', hookData?.table || params.table);
161
+ const index = template?.find(el => el[0] === 'index.yml')?.[1] || {};
162
+
163
+ const html = {};
164
+ const { panels = [] } = index;
165
+
166
+ if (template && (hookData?.id || params.id)) {
167
+
168
+ // tokens result
169
+ const tokens = {};
170
+ if (index?.tokens && typeof index?.tokens === 'object' && !Array.isArray(index?.tokens)) {
171
+ Object.keys(index.tokens || {})
172
+ .filter(key => index?.tokens[key]?.public
173
+ || actions?.includes?.('edit')
174
+ || actions?.includes?.('add')
175
+ || !index?.tokens[key]?.table
176
+ )
177
+ .forEach(key => {
178
+ const item = index?.tokens[key];
179
+ Object.keys(item).filter(el => item[el]?.includes?.('{{')).forEach(el => {
180
+ item[el] = handlebarsSync.compile(item[el])({ user, uid: user?.uid, id, data: rows[0] });
181
+ });
182
+
183
+ const token = item.form && item.table ? setToken({
184
+ ids: [JSON.stringify(item)],
185
+ uid,
186
+ array: 1,
187
+ })[0] : setOpt(item, user.uid);
188
+ tokens[key] = token;
189
+ });
190
+ }
191
+
192
+ // conditions
193
+ panels?.filter(el => el.items).forEach(el => {
194
+ el.items = el.items?.filter(el => conditions(el.conditions, rows[0]));
195
+ });
196
+
197
+ // title, count
198
+ panels?.filter(el => el.items).forEach(async el => {
199
+ const filtered = el.items.filter(el => el.count?.toLowerCase?.().includes('select'));
200
+ const data = await Promise.all(filtered.map(el => pg.query(el.count).then(el => el.rows[0] || {})))
201
+ filtered.forEach((el, i) => {
202
+ Object.assign(el, data[i] || {}, data[i].count ? {} : { count: undefined })
203
+ });
204
+ const q = el.items.map((el) => el.component ? components[el.component] : null).filter(el => el).join(' union all ');
205
+ const counts = q && id
206
+ ? await pg.query(q, [id])
207
+ .then(e => e.rows.reduce((acc, curr) => Object.assign(acc, { [curr.component]: curr.count }), {}))
208
+ : {};
209
+ el.items?.filter?.(item => item.component)?.forEach(item => Object.assign(item, { count: counts?.[item.component] }));
210
+ });
211
+
212
+ // data result
213
+ const data = {};
214
+ const route = await pg.query(`select route_id as path, title from admin.routes where enabled and alias=$1 limit 1`, [table])
215
+ .then(el => el.rows?.[0] || {});
216
+ Object.assign(route, { tableTitle: loadTable?.title });
217
+ if (index?.data && index?.data?.[0]?.name) {
218
+ await Promise.all(index.data.filter((el) => el?.name && el?.sql).map(async (el) => {
219
+ const q = handlebarsSync.compile(el.sql)({ data: rows[0], user, uid: user?.uid, id });
220
+ const { rows: sqlData } = await pg.query(q);
221
+ data[el.name] = sqlData;
222
+ }));
223
+ }
224
+
225
+ // html
226
+ await Promise.all(template.filter(el => el[0].includes('.hbs')).map(async (el) => {
227
+ const htmlContent = await handlebars.compile(el[1])({ ...rows[0], user, data, tokens });
228
+ const name = el[0].substring(0, el[0].lastIndexOf('.'))
229
+ html[name] = htmlContent;
230
+ }));
231
+ }
232
+
153
233
  const res = {
154
- time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, status, rows, meta, columns, filters,
234
+ time: Date.now() - time,
235
+ public: ispublic,
236
+ card: loadTable.card,
237
+ actions,
238
+ total,
239
+ filtered,
240
+ count: rows.length,
241
+ pk,
242
+ form,
243
+ agg,
244
+ status,
245
+ panels,
246
+ html,
247
+ rows,
248
+ meta,
249
+ columns,
250
+ filters,
155
251
  };
156
252
 
157
253
  // console.log({ add: loadTable.table, form: loadTable.form });
@@ -1,67 +1,67 @@
1
- import { getSelect, getFilterSQL, getTemplate, getSelectVal, pgClients } from '../../../../utils.js';
2
-
3
- export default async function filterAPI(req) {
4
- const time = Date.now();
5
-
6
- const {
7
- params, query = {}, pg = pgClients.client, user = {},
8
- } = req;
9
-
10
- const loadTable = await getTemplate('table', params.table);
11
- if (!loadTable) { return { status: 404, message: 'not found' }; }
12
-
13
- const sqlTable = loadTable.sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', user?.uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
14
- const { fields: columns } = await pg.query(`select * from ${loadTable.table} t ${sqlTable} limit 0`);
15
-
16
- const {
17
- filter, custom, state, search,
18
- } = query;
19
-
20
- const { optimizedSQL = `select * from ${loadTable.table}` } = loadTable?.sql || filter || custom || state || search ? await getFilterSQL({
21
- pg,
22
- table: params.table,
23
- filter,
24
- custom,
25
- state,
26
- search,
27
- }) : {};
28
-
29
- const filters = loadTable?.filter_list || loadTable?.filters || loadTable?.filterList || [];
30
- await Promise.all(filters.filter((el) => el.data && (el.id || el.name)).map(async (el) => {
31
- const name = el.id || el.name;
32
- const cls = await getSelect(el.data, pg);
33
-
34
- if (!cls || !loadTable.table) return;
35
- const { dataTypeID } = columns.find((item) => item.name === name) || {};
36
-
37
- const countArr = pg.pgType[dataTypeID]?.includes('[]')
38
- ? await pg.queryCache(`select unnest(${name})::text as id,count(*) from (${optimizedSQL})q group by unnest(${name})`, { table: loadTable.table, time: 5 })
39
- : await pg.queryCache(`select ${name}::text as id,count(*) from (${optimizedSQL})q group by ${name}`, { table: loadTable.table, time: 5 });
40
- const ids = countArr.rows.map(el1 => el1.id);
41
-
42
- const clsData = await getSelectVal({ pg, values: ids, name: el.data });
43
-
44
- const options = countArr.rows.map(cel => {
45
- const data = cls?.arr?.find(c => c.id === cel.id) || { text: clsData[cel.id] };
46
- return { ...cel, ...data };
47
- });
48
- Object.assign(el, { options });
49
- }));
50
-
51
- const q = ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).map((el) => `select count(*), '${el.name}' as name from (${optimizedSQL})q where ${el.sql}`).join(' union all ');
52
- const { rows = [] } = q ? await pg.query(q) : {};
53
- if (rows?.length) {
54
- ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).forEach((el) => {
55
- const { count } = rows.find((row) => row.name === el.name) || {};
56
- Object.assign(el, { count, sql: undefined });
57
- });
58
- }
59
-
60
- return {
61
- time: Date.now() - time,
62
- list: filters,
63
- custom: loadTable?.filterCustom,
64
- inline: loadTable?.filterInline,
65
- state: loadTable?.filterState,
66
- };
67
- }
1
+ import { getSelect, getFilterSQL, getTemplate, getSelectVal, pgClients } from '../../../../utils.js';
2
+
3
+ export default async function filterAPI(req) {
4
+ const time = Date.now();
5
+
6
+ const {
7
+ params, query = {}, pg = pgClients.client, user = {},
8
+ } = req;
9
+
10
+ const loadTable = await getTemplate('table', params.table);
11
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
12
+
13
+ const sqlTable = loadTable.sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', user?.uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
14
+ const { fields: columns } = await pg.query(`select * from ${loadTable.table} t ${sqlTable} limit 0`);
15
+
16
+ const {
17
+ filter, custom, state, search,
18
+ } = query;
19
+
20
+ const { optimizedSQL = `select * from ${loadTable.table}` } = loadTable?.sql || filter || custom || state || search ? await getFilterSQL({
21
+ pg,
22
+ table: params.table,
23
+ filter,
24
+ custom,
25
+ state,
26
+ search,
27
+ }) : {};
28
+
29
+ const filters = loadTable?.filter_list || loadTable?.filters || loadTable?.filterList || [];
30
+ await Promise.all(filters.filter((el) => el.data && (el.id || el.name)).map(async (el) => {
31
+ const name = el.id || el.name;
32
+ const cls = await getSelect(el.data, pg);
33
+
34
+ if (!cls || !loadTable.table) return;
35
+ const { dataTypeID } = columns.find((item) => item.name === name) || {};
36
+
37
+ const countArr = pg.pgType[dataTypeID]?.includes('[]')
38
+ ? await pg.queryCache(`select unnest(${name})::text as id,count(*) from (${optimizedSQL})q group by unnest(${name})`, { table: loadTable.table, time: 5 })
39
+ : await pg.queryCache(`select ${name}::text as id,count(*) from (${optimizedSQL})q group by ${name}`, { table: loadTable.table, time: 5 });
40
+ const ids = countArr.rows.map(el1 => el1.id);
41
+
42
+ const clsData = await getSelectVal({ pg, values: ids, name: el.data });
43
+
44
+ const options = countArr.rows.map(cel => {
45
+ const data = cls?.arr?.find(c => c.id === cel.id) || { text: clsData[cel.id] };
46
+ return { ...cel, ...data };
47
+ });
48
+ Object.assign(el, { options });
49
+ }));
50
+
51
+ const q = ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).map((el) => `select count(*), '${el.name}' as name from (${optimizedSQL})q where ${el.sql}`).join(' union all ');
52
+ const { rows = [] } = q ? await pg.query(q) : {};
53
+ if (rows?.length) {
54
+ ((loadTable?.filterState || []).concat(loadTable?.filterCustom || [])).filter((el) => el.name && el.sql).forEach((el) => {
55
+ const { count } = rows.find((row) => row.name === el.name) || {};
56
+ Object.assign(el, { count, sql: undefined });
57
+ });
58
+ }
59
+
60
+ return {
61
+ time: Date.now() - time,
62
+ list: filters,
63
+ custom: loadTable?.filterCustom,
64
+ inline: loadTable?.filterInline,
65
+ state: loadTable?.filterState,
66
+ };
67
+ }
@@ -1,42 +1,42 @@
1
- import { applyHook, getTemplate } from '../../../../utils.js';
2
-
3
- const sql = `select property_key as key, property_json as json, property_int as int,
4
- property_text as text from admin.properties where 1=1`;
5
-
6
- async function getSettings({ pg }) {
7
- const { rows = [] } = await pg.query(sql);
8
- const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
- return data;
10
- }
11
-
12
- export default async function formFunction(req) {
13
- const time = Date.now();
14
-
15
- const { pg, params, user } = req;
16
- const hookData = await applyHook('preForm', { form: params?.form, user });
17
-
18
- if (hookData?.message && hookData?.status) {
19
- return { message: hookData?.message, status: hookData?.status };
20
- }
21
-
22
- const form = await getTemplate('form', hookData?.form || params?.form);
23
- if (!form) { return { status: 404, message: 'not found' }; }
24
-
25
- // replace settings
26
- const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
- if (arr?.length) {
28
- const string = JSON.stringify(form);
29
- const settings = await getSettings({ pg });
30
- const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
- const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
- return { time: Date.now() - time, form: JSON.parse(res) };
33
- }
34
-
35
- const res = { time: Date.now() - time, form };
36
- const res1 = await applyHook('afterForm', {
37
- form: hookData?.form || params?.form,
38
- payload: res,
39
- user,
40
- });
41
- return res1 || { time: Date.now() - time, form };
42
- }
1
+ import { applyHook, getTemplate } from '../../../../utils.js';
2
+
3
+ const sql = `select property_key as key, property_json as json, property_int as int,
4
+ property_text as text from admin.properties where 1=1`;
5
+
6
+ async function getSettings({ pg }) {
7
+ const { rows = [] } = await pg.query(sql);
8
+ const data = rows.reduce((acc, curr) => Object.assign(acc, { [curr.key]: curr.json || curr.int || curr.text }), {});
9
+ return data;
10
+ }
11
+
12
+ export default async function formFunction(req) {
13
+ const time = Date.now();
14
+
15
+ const { pg, params, user } = req;
16
+ const hookData = await applyHook('preForm', { form: params?.form, user });
17
+
18
+ if (hookData?.message && hookData?.status) {
19
+ return { message: hookData?.message, status: hookData?.status };
20
+ }
21
+
22
+ const form = await getTemplate('form', hookData?.form || params?.form);
23
+ if (!form) { return { status: 404, message: 'not found' }; }
24
+
25
+ // replace settings
26
+ const arr = JSON.stringify(form).match(/{{settings.([^}]*)}}/g);
27
+ if (arr?.length) {
28
+ const string = JSON.stringify(form);
29
+ const settings = await getSettings({ pg });
30
+ const match = arr.reduce((acc, curr) => Object.assign(acc, { [curr]: settings[curr.replace(/^{{settings./g, '').replace(/}}$/, '')] }), {});
31
+ const res = Object.keys(match).reduce((s, m) => s.replace(m, match[m]), string);
32
+ return { time: Date.now() - time, form: JSON.parse(res) };
33
+ }
34
+
35
+ const res = { time: Date.now() - time, form };
36
+ const res1 = await applyHook('afterForm', {
37
+ form: hookData?.form || params?.form,
38
+ payload: res,
39
+ user,
40
+ });
41
+ return res1 || { time: Date.now() - time, form };
42
+ }
@@ -1,74 +1,74 @@
1
- import {
2
- getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
- } from '../../../../utils.js';
4
-
5
- function sequence(tables, data, fn) {
6
- return tables.reduce((promise, table) => promise.then(() => fn({
7
- ...data, tableName: table.replace('.json', ''),
8
- })), Promise.resolve());
9
- }
10
-
11
- async function getData({
12
- pg, tableName, query = {}, maxLimit, res,
13
- }) {
14
- const loadTable = await getTemplate('table', tableName);
15
-
16
- if (!loadTable) { return { message: 'not found', status: 404 }; }
17
-
18
- const {
19
- table, columns, meta,
20
- } = loadTable;
21
-
22
- const { pk } = await getMeta(table);
23
-
24
- const cols = columns.map((el) => el.name || el).join(',');
25
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
- const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
-
28
- const limit = Math.max(maxLimit - res.rows.length, 0);
29
- // Math.max(query.offset - res.rows.length,0)
30
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
-
32
- const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
-
34
- const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
- const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
- if (query.sql) {
37
- res.sql.push(q);
38
- return null;
39
- }
40
-
41
- const { rows } = await pg.query(q);
42
-
43
- const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
-
45
- await metaFormat({ rows, table: tableName });
46
- res.total += +total;
47
- rows.forEach((row) => {
48
- const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
- res.rows.push({
50
- ...row, register: tableName, register_title: loadTable.ua, href,
51
- });
52
- });
53
- return null;
54
- }
55
-
56
- export default async function search({
57
- pg, funcs, query = {},
58
- }) {
59
- const time = Date.now();
60
-
61
- const tables = query.table ? [query.table] : await getTemplates('table');
62
- const res = { rows: [], sql: [], total: 0 };
63
-
64
- const maxLimit = Math.min(100, query.limit || '16');
65
- await sequence(tables, {
66
- pg, funcs, query, maxLimit, res,
67
- }, getData);
68
-
69
- if (query.sql) return res.sql.join(';\n');
70
-
71
- return {
72
- time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
- };
74
- }
1
+ import {
2
+ getMeta, metaFormat, getTemplates, getTemplate, handlebars,
3
+ } from '../../../../utils.js';
4
+
5
+ function sequence(tables, data, fn) {
6
+ return tables.reduce((promise, table) => promise.then(() => fn({
7
+ ...data, tableName: table.replace('.json', ''),
8
+ })), Promise.resolve());
9
+ }
10
+
11
+ async function getData({
12
+ pg, tableName, query = {}, maxLimit, res,
13
+ }) {
14
+ const loadTable = await getTemplate('table', tableName);
15
+
16
+ if (!loadTable) { return { message: 'not found', status: 404 }; }
17
+
18
+ const {
19
+ table, columns, meta,
20
+ } = loadTable;
21
+
22
+ const { pk } = await getMeta(table);
23
+
24
+ const cols = columns.map((el) => el.name || el).join(',');
25
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split('-');
26
+ const order = cols.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
27
+
28
+ const limit = Math.max(maxLimit - res.rows.length, 0);
29
+ // Math.max(query.offset - res.rows.length,0)
30
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
31
+
32
+ const search1 = meta?.search && query.key ? `(${meta?.search.concat(meta?.title ? `,${meta?.title}` : '').split(',').map(el => `${el} ilike '%${query.key}%'`).join(' or ')})` : 'false';
33
+
34
+ const where = [!pk ? 'false' : 'true', loadTable.query, search1].filter((el) => el);
35
+ const q = `select ${[`"${pk}" as id`, meta?.title ? `${meta.title} as title` : ''].filter((el) => el).join(',')} from ${table} t where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
36
+ if (query.sql) {
37
+ res.sql.push(q);
38
+ return null;
39
+ }
40
+
41
+ const { rows } = await pg.query(q);
42
+
43
+ const total = await pg.queryCache(`select count(*) from ${table} t where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count) || 0;
44
+
45
+ await metaFormat({ rows, table: tableName });
46
+ res.total += +total;
47
+ rows.forEach((row) => {
48
+ const href = meta?.href ? handlebars.compile(meta.href)({ ...row, [pk]: row.id }) : undefined;
49
+ res.rows.push({
50
+ ...row, register: tableName, register_title: loadTable.ua, href,
51
+ });
52
+ });
53
+ return null;
54
+ }
55
+
56
+ export default async function search({
57
+ pg, funcs, query = {},
58
+ }) {
59
+ const time = Date.now();
60
+
61
+ const tables = query.table ? [query.table] : await getTemplates('table');
62
+ const res = { rows: [], sql: [], total: 0 };
63
+
64
+ const maxLimit = Math.min(100, query.limit || '16');
65
+ await sequence(tables, {
66
+ pg, funcs, query, maxLimit, res,
67
+ }, getData);
68
+
69
+ if (query.sql) return res.sql.join(';\n');
70
+
71
+ return {
72
+ time: Date.now() - time, total: res.total, count: res.rows.length, rows: res.rows,
73
+ };
74
+ }