@opengis/fastify-table 1.1.136 → 1.1.138

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 (67) 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/properties.sql +144 -144
  7. package/server/migrations/users.sql +173 -173
  8. package/server/plugins/cron/funcs/addCron.js +130 -130
  9. package/server/plugins/cron/index.js +6 -6
  10. package/server/plugins/crud/funcs/dataDelete.js +23 -23
  11. package/server/plugins/crud/funcs/dataInsert.js +45 -45
  12. package/server/plugins/crud/funcs/dataUpdate.js +65 -65
  13. package/server/plugins/crud/funcs/getOpt.js +13 -13
  14. package/server/plugins/crud/funcs/setOpt.js +21 -21
  15. package/server/plugins/crud/funcs/setToken.js +44 -44
  16. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  17. package/server/plugins/crud/funcs/utils/logChanges.js +96 -62
  18. package/server/plugins/crud/index.js +23 -23
  19. package/server/plugins/hook/index.js +8 -8
  20. package/server/plugins/logger/errorStatus.js +19 -19
  21. package/server/plugins/logger/index.js +21 -21
  22. package/server/plugins/migration/funcs/exec.migrations.js +86 -86
  23. package/server/plugins/migration/index.js +7 -7
  24. package/server/plugins/pg/pgClients.js +21 -21
  25. package/server/plugins/policy/index.js +12 -12
  26. package/server/plugins/policy/sqlInjection.js +33 -33
  27. package/server/plugins/redis/client.js +8 -8
  28. package/server/plugins/redis/funcs/redisClients.js +3 -3
  29. package/server/plugins/redis/index.js +17 -17
  30. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  31. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  32. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +171 -171
  33. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  34. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  35. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  36. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  37. package/server/plugins/table/funcs/getTemplates.js +19 -19
  38. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  39. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  40. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  41. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +50 -50
  42. package/server/plugins/table/funcs/metaFormat/index.js +45 -45
  43. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  44. package/server/plugins/table/index.js +13 -13
  45. package/server/plugins/util/index.js +7 -7
  46. package/server/routes/cron/index.js +14 -14
  47. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  48. package/server/routes/crud/controllers/insert.js +6 -2
  49. package/server/routes/crud/controllers/table.js +91 -91
  50. package/server/routes/crud/controllers/update.js +6 -2
  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 +157 -156
  59. package/server/routes/table/controllers/filter.js +66 -66
  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 +158 -158
  63. package/server/routes/table/index.js +29 -29
  64. package/server/routes/table/schema.js +64 -64
  65. package/server/routes/util/controllers/status.monitor.js +8 -8
  66. package/server/routes/util/index.js +11 -11
  67. package/utils.js +125 -122
@@ -1,23 +1,23 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import getRedis from '../../redis/funcs/getRedis.js';
4
-
5
- import logChanges from './utils/logChanges.js';
6
-
7
- const rclient = getRedis();
8
-
9
- export default async function dataDelete({
10
- table, id, pg: pg1, uid,
11
- }) {
12
- const pg = pg1 || getPG({ name: 'client' });
13
- const { pk } = await getMeta({ pg, table });
14
- if (!pg.tlist?.includes(table)) return 'table not exist';
15
- const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
16
- // console.log(updateDataset);
17
- const res = await pg.query(delQuery, [id]).then(el => el.rows?.[0] || {});
18
- await logChanges({
19
- pg, table, id, uid, type: 'DELETE',
20
- });
21
- rclient.incr(`pg:${table}:crud`);
22
- return res;
23
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import getRedis from '../../redis/funcs/getRedis.js';
4
+
5
+ import logChanges from './utils/logChanges.js';
6
+
7
+ const rclient = getRedis();
8
+
9
+ export default async function dataDelete({
10
+ table, template, id, pg: pg1, uid,
11
+ }) {
12
+ const pg = pg1 || getPG({ name: 'client' });
13
+ const { pk } = await getMeta({ pg, table });
14
+ if (!pg.tlist?.includes(table)) return 'table not exist';
15
+ const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
16
+ // console.log(updateDataset);
17
+ const res = await pg.query(delQuery, [id]).then(el => el.rows?.[0] || {});
18
+ await logChanges({
19
+ pg, table, template, id, uid, type: 'DELETE',
20
+ });
21
+ rclient.incr(`pg:${table}:crud`);
22
+ return res;
23
+ }
@@ -1,45 +1,45 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import getRedis from '../../redis/funcs/getRedis.js';
4
-
5
- import logChanges from './utils/logChanges.js';
6
-
7
- const rclient = getRedis();
8
-
9
- export default async function dataInsert({
10
- id, table, data, pg: pg1, uid,
11
- }) {
12
- const pg = pg1 || getPG({ name: 'client' });
13
- if (!data) return null;
14
- const { columns } = await getMeta({ pg, table });
15
- if (!columns) return null;
16
-
17
- const names = columns.map((el) => el.name);
18
-
19
- Object.assign(data, {
20
- ...(id && pg.pk?.[table] ? { [pg.pk?.[table]]: id } : {}),
21
- ...(table !== 'admin.users' ? { uid } : {}),
22
- // editor_id: uid,
23
- });
24
- const systemColumns = ['cdate', 'editor_date'].filter((el) => names.includes(el)).map((el) => [el, 'now()']);
25
-
26
- const filterData = Object.keys(data)
27
- .filter((el) => !['cdate', 'editor_date'].includes(el) && (typeof data[el] === 'boolean' ? true : data[el]) && names.includes(el)).map((el) => [el, data[el]]);
28
-
29
- const insertQuery = `insert into ${table}
30
-
31
- ( ${filterData?.map((key) => `"${key[0]}"`).concat(systemColumns.map((el) => el[0])).join(',')})
32
-
33
- values (${filterData?.map((key, i) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).concat(systemColumns.map((el) => el[1])).join(',')})
34
-
35
- returning *`;
36
-
37
- const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
38
-
39
- await logChanges({
40
- pg, table, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
41
- });
42
-
43
- rclient.incr(`pg:${table}:crud`);
44
- return res;
45
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import getRedis from '../../redis/funcs/getRedis.js';
4
+
5
+ import logChanges from './utils/logChanges.js';
6
+
7
+ const rclient = getRedis();
8
+
9
+ export default async function dataInsert({
10
+ id, table, template, data, pg: pg1, uid,
11
+ }) {
12
+ const pg = pg1 || getPG({ name: 'client' });
13
+ if (!data) return null;
14
+ const { columns } = await getMeta({ pg, table });
15
+ if (!columns) return null;
16
+
17
+ const names = columns.map((el) => el.name);
18
+
19
+ Object.assign(data, {
20
+ ...(id && pg.pk?.[table] ? { [pg.pk?.[table]]: id } : {}),
21
+ ...(table !== 'admin.users' ? { uid } : {}),
22
+ // editor_id: uid,
23
+ });
24
+ const systemColumns = ['cdate', 'editor_date'].filter((el) => names.includes(el)).map((el) => [el, 'now()']);
25
+
26
+ const filterData = Object.keys(data)
27
+ .filter((el) => !['cdate', 'editor_date'].includes(el) && (typeof data[el] === 'boolean' ? true : data[el]) && names.includes(el)).map((el) => [el, data[el]]);
28
+
29
+ const insertQuery = `insert into ${table}
30
+
31
+ ( ${filterData?.map((key) => `"${key[0]}"`).concat(systemColumns.map((el) => el[0])).join(',')})
32
+
33
+ values (${filterData?.map((key, i) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).concat(systemColumns.map((el) => el[1])).join(',')})
34
+
35
+ returning *`;
36
+
37
+ const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
38
+
39
+ await logChanges({
40
+ pg, table, template, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
41
+ });
42
+
43
+ rclient.incr(`pg:${table}:crud`);
44
+ return res;
45
+ }
@@ -1,65 +1,65 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import getRedis from '../../redis/funcs/getRedis.js';
4
-
5
- import logChanges from './utils/logChanges.js';
6
-
7
- const rclient = getRedis();
8
- const srids = {};
9
-
10
- function assignValue(key, i, srid = 4326, columnType = 'text') {
11
- if (key === 'geom' && columnType === 'geometry') {
12
- return `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)`;
13
- }
14
- if (key?.includes('geom') && columnType === 'geometry') {
15
- return `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),${srid})`;
16
- }
17
- return `"${key}"=$${i + 2}`;
18
- }
19
-
20
- export default async function dataUpdate({
21
- table, id, data, pg: pg1, uid,
22
- }) {
23
- if (!data || !table || !id) return null;
24
-
25
- const pg = pg1 || getPG({ name: 'client' });
26
- const { columns, pk } = await getMeta({ pg, table });
27
-
28
- const names = columns?.map((el) => el.name);
29
-
30
- const filterData = Object.keys(data)
31
- .filter((el) => (/* typeof data[el] === 'boolean' ? true : data[el] && */ names?.includes(el) && !['editor_date', 'editor_id'].includes(el)));
32
-
33
- const systemColumns = [['editor_date', 'now()'], uid ? ['editor_id', `'${uid.replace(/'/g, "''")}'`] : []].filter((el) => names.includes(el[0])).map((el) => `${el[0]} = ${el[1]}`).join(',');
34
-
35
- const filterValue = filterData.map((el) => {
36
- const { dataTypeID = 25 } = columns?.find?.((col) => col?.name === el) || {};
37
- if (pg.pgType[dataTypeID]?.endsWith('[]') && ['string', 'number'].includes(typeof data[el])) {
38
- Object.assign(data, { [el]: data[el].split(',') });
39
- }
40
- return [el, data[el]];
41
- }).map((el) => (typeof el[1] === 'object' && el[1] && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
42
-
43
- // update geometry with srid
44
- if (!srids[table]) {
45
- const { srids1 } = await pg.query(`select json_object_agg(_table,rel) as srids1 from (
46
- select f_table_schema||'.'||f_table_name as _table,
47
- json_object_agg(f_geometry_column, case when srid = 0 then 4326 else srid end) as rel
48
- from public.geometry_columns group by f_table_schema||'.'||f_table_name
49
- )q`).then((res1) => res1.rows?.[0] || {});
50
- Object.assign(srids, srids1);
51
- }
52
-
53
- const updateQuery = `UPDATE ${table} SET ${systemColumns ? `${systemColumns}${filterData?.length ? ',' : ''}` : ''}
54
- ${filterData?.map((key, i) => assignValue(key, i, srids[table]?.[key] || 4326, pg.pgType?.[columns.find(col => col.name === key)?.dataTypeID || '']))?.join(',')}
55
- WHERE ${pk} = $1 returning *`;
56
- // console.log(updateQuery, filterValue);
57
- const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
58
-
59
- await logChanges({
60
- pg, table, data, id, uid, type: 'UPDATE',
61
- });
62
-
63
- rclient.incr(`pg:${table}:crud`);
64
- return res;
65
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import getRedis from '../../redis/funcs/getRedis.js';
4
+
5
+ import logChanges from './utils/logChanges.js';
6
+
7
+ const rclient = getRedis();
8
+ const srids = {};
9
+
10
+ function assignValue(key, i, srid = 4326, columnType = 'text') {
11
+ if (key === 'geom' && columnType === 'geometry') {
12
+ return `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)`;
13
+ }
14
+ if (key?.includes('geom') && columnType === 'geometry') {
15
+ return `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),${srid})`;
16
+ }
17
+ return `"${key}"=$${i + 2}`;
18
+ }
19
+
20
+ export default async function dataUpdate({
21
+ table, template, id, data, pg: pg1, uid,
22
+ }) {
23
+ if (!data || !table || !id) return null;
24
+
25
+ const pg = pg1 || getPG({ name: 'client' });
26
+ const { columns, pk } = await getMeta({ pg, table });
27
+
28
+ const names = columns?.map((el) => el.name);
29
+
30
+ const filterData = Object.keys(data)
31
+ .filter((el) => (/* typeof data[el] === 'boolean' ? true : data[el] && */ names?.includes(el) && !['editor_date', 'editor_id'].includes(el)));
32
+
33
+ const systemColumns = [['editor_date', 'now()'], uid ? ['editor_id', `'${uid.replace(/'/g, "''")}'`] : []].filter((el) => names.includes(el[0])).map((el) => `${el[0]} = ${el[1]}`).join(',');
34
+
35
+ const filterValue = filterData.map((el) => {
36
+ const { dataTypeID = 25 } = columns?.find?.((col) => col?.name === el) || {};
37
+ if (pg.pgType[dataTypeID]?.endsWith('[]') && ['string', 'number'].includes(typeof data[el])) {
38
+ Object.assign(data, { [el]: data[el].split(',') });
39
+ }
40
+ return [el, data[el]];
41
+ }).map((el) => (typeof el[1] === 'object' && el[1] && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
42
+
43
+ // update geometry with srid
44
+ if (!srids[table]) {
45
+ const { srids1 } = await pg.query(`select json_object_agg(_table,rel) as srids1 from (
46
+ select f_table_schema||'.'||f_table_name as _table,
47
+ json_object_agg(f_geometry_column, case when srid = 0 then 4326 else srid end) as rel
48
+ from public.geometry_columns group by f_table_schema||'.'||f_table_name
49
+ )q`).then((res1) => res1.rows?.[0] || {});
50
+ Object.assign(srids, srids1);
51
+ }
52
+
53
+ const updateQuery = `UPDATE ${table} SET ${systemColumns ? `${systemColumns}${filterData?.length ? ',' : ''}` : ''}
54
+ ${filterData?.map((key, i) => assignValue(key, i, srids[table]?.[key] || 4326, pg.pgType?.[columns.find(col => col.name === key)?.dataTypeID || '']))?.join(',')}
55
+ WHERE ${pk} = $1 returning *`;
56
+ // console.log(updateQuery, filterValue);
57
+ const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
58
+
59
+ await logChanges({
60
+ pg, table, template, data, id, uid, type: 'UPDATE',
61
+ });
62
+
63
+ rclient.incr(`pg:${table}:crud`);
64
+ return res;
65
+ }
@@ -1,13 +1,13 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
-
3
- // import { getRedis } from '../../../../utils.js';
4
-
5
- export default async function getOpt(token, uid = 0) {
6
- const rclient = getRedis({ db: 0 });
7
-
8
- const key = `opt:${uid}:${token}`;
9
- // console.log(key);
10
- const data = await rclient.get(key);
11
- if (!data) return null;
12
- return JSON.parse(data);
13
- }
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+
3
+ // import { getRedis } from '../../../../utils.js';
4
+
5
+ export default async function getOpt(token, uid = 0) {
6
+ const rclient = getRedis({ db: 0 });
7
+
8
+ const key = `opt:${uid}:${token}`;
9
+ // console.log(key);
10
+ const data = await rclient.get(key);
11
+ if (!data) return null;
12
+ return JSON.parse(data);
13
+ }
@@ -1,21 +1,21 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- const random = randomUUID();
4
-
5
- import getRedis from '../../redis/funcs/getRedis.js';
6
-
7
- // import { getRedis } from '../../../../utils.js';
8
-
9
- function md5(string) {
10
- return createHash('md5').update(string).digest('hex');
11
- }
12
-
13
- export default function setOpt(params, uid = 0) {
14
- const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params) + random, 'hex').toString('base64').replace(/[+-=]+/g, '');
15
- // const token = md5(params);
16
- const key = `opt:${uid}:${token}`;
17
-
18
- const rclient = getRedis({ db: 0 });
19
- rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
20
- return token;
21
- }
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ const random = randomUUID();
4
+
5
+ import getRedis from '../../redis/funcs/getRedis.js';
6
+
7
+ // import { getRedis } from '../../../../utils.js';
8
+
9
+ function md5(string) {
10
+ return createHash('md5').update(string).digest('hex');
11
+ }
12
+
13
+ export default function setOpt(params, uid = 0) {
14
+ const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params) + random, 'hex').toString('base64').replace(/[+-=]+/g, '');
15
+ // const token = md5(params);
16
+ const key = `opt:${uid}:${token}`;
17
+
18
+ const rclient = getRedis({ db: 0 });
19
+ rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
20
+ return token;
21
+ }
@@ -1,44 +1,44 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- import config from '../../../../config.js';
4
-
5
- import getRedis from '../../redis/funcs/getRedis.js';
6
-
7
- const rclient = getRedis({ db: 0 });
8
-
9
- // import { config, getRedis } from '../../../../utils.js';
10
-
11
- const generateCodes = (ids, userToken) => {
12
- const token = userToken || randomUUID();
13
- const notNullIds = ids.filter((el) => el);
14
- const obj = {};
15
- const codes = notNullIds.reduce((acc, id) => {
16
- const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
17
- acc[newToken] = id; obj[id] = newToken;
18
- return acc;
19
- }, {});
20
- return { codes, obj };
21
- };
22
-
23
- function setToken({
24
- ids: idsOrigin, uid, array,
25
- }) {
26
- // const rclient5 = getRedis({ db: 0, funcs });
27
-
28
- if (!uid) return { user: 'empty' };
29
- if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
30
-
31
- const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
32
-
33
- // TODO generate salt
34
- const { codes, obj } = generateCodes(ids, uid);
35
-
36
- if (!Object.keys(codes).length) return { ids: 'empty' };
37
-
38
- rclient.hmset(`${config.pg.database}:token:edit:${uid}`, codes);
39
- // console.log(`${config.pg.database}:token:edit:${uid}`, idsOrigin, Object.values(obj));
40
- // TODO дополнительно писать в hset token -> uid
41
- return array ? Object.values(obj) : obj;
42
- }
43
-
44
- export default setToken;
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import config from '../../../../config.js';
4
+
5
+ import getRedis from '../../redis/funcs/getRedis.js';
6
+
7
+ const rclient = getRedis({ db: 0 });
8
+
9
+ // import { config, getRedis } from '../../../../utils.js';
10
+
11
+ const generateCodes = (ids, userToken) => {
12
+ const token = userToken || randomUUID();
13
+ const notNullIds = ids.filter((el) => el);
14
+ const obj = {};
15
+ const codes = notNullIds.reduce((acc, id) => {
16
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
17
+ acc[newToken] = id; obj[id] = newToken;
18
+ return acc;
19
+ }, {});
20
+ return { codes, obj };
21
+ };
22
+
23
+ function setToken({
24
+ ids: idsOrigin, uid, array,
25
+ }) {
26
+ // const rclient5 = getRedis({ db: 0, funcs });
27
+
28
+ if (!uid) return { user: 'empty' };
29
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
30
+
31
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
32
+
33
+ // TODO generate salt
34
+ const { codes, obj } = generateCodes(ids, uid);
35
+
36
+ if (!Object.keys(codes).length) return { ids: 'empty' };
37
+
38
+ rclient.hmset(`${config.pg.database}:token:edit:${uid}`, codes);
39
+ // console.log(`${config.pg.database}:token:edit:${uid}`, idsOrigin, Object.values(obj));
40
+ // TODO дополнительно писать в hset token -> uid
41
+ return array ? Object.values(obj) : obj;
42
+ }
43
+
44
+ export default setToken;
@@ -1,10 +1,10 @@
1
- import path from 'node:path';
2
-
3
- import config from '../../../../../config.js';
4
-
5
- export default function getFolder(req, type = 'server') {
6
- if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
7
- const types = { local: req.root || config.root, server: req.mapServerRoot || config.mapServerRoot };
8
- const filepath = path.posix.join(types[type] || `/data/local/${req.pg?.options?.database || ''}`, req.folder || config.folder || '');
9
- return filepath;
10
- }
1
+ import path from 'node:path';
2
+
3
+ import config from '../../../../../config.js';
4
+
5
+ export default function getFolder(req, type = 'server') {
6
+ if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
7
+ const types = { local: req.root || config.root, server: req.mapServerRoot || config.mapServerRoot };
8
+ const filepath = path.posix.join(types[type] || `/data/local/${req.pg?.options?.database || ''}`, req.folder || config.folder || '');
9
+ return filepath;
10
+ }
@@ -1,62 +1,96 @@
1
- import getMeta from '../../../pg/funcs/getMeta.js';
2
-
3
- export default async function logChanges({
4
- pg, table, id, data, uid = 1, type,
5
- }) {
6
- if (!id) {
7
- console.error('param id is required');
8
- return null;
9
- }
10
- if (!table || !pg.pk?.[table]) {
11
- console.error('table not found');
12
- return null;
13
- }
14
- if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
15
- console.error('log table not found');
16
- return null;
17
- }
18
- if (!type) {
19
- console.error('invalid type');
20
- return null;
21
- }
22
-
23
- try {
24
- const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
25
- values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
26
-
27
- const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
28
- const columnList = fields.map((el) => el?.name);
29
- const q = `select ${Object.keys(data || {}).filter((el) => columnList.includes(el)).map(el => `"${el.replace(/'/g, "''")}"`).join(',') || '*'} from ${table} where ${pg.pk?.[table]}=$1`;
30
- // console.log(q, type, id);
31
-
32
- const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
33
-
34
- const { columns = [] } = await getMeta({ table: 'log.table_changes_data' });
35
- const names = columns.map((el) => el.name);
36
-
37
- const res = await Promise.all(Object.keys(data || {}).map(async (el) => {
38
- const filterData = Object.entries({
39
- change_id: changeId, entity_key: el, value_old: old[el], value_new: data[el], uid,
40
- })
41
- .filter((el1) => el1[1] && names.includes(el1[0]));
42
-
43
- const insertQuery = `insert into log.table_changes_data (${filterData?.map((key) => `"${key[0]}"`).join(',')})
44
- values (${filterData?.map((key, i) => `$${i + 1}`).join(',')}) returning *`;
45
-
46
- const { rows = [] } = await pg.query(insertQuery, [...filterData.map((el1) => (el1[1] && typeof el1[1] === 'object' && (!Array.isArray(el1[1]) || typeof el1[1]?.[0] === 'object') ? JSON.stringify(el1[1]) : el1[1]))]) || {};
47
- return rows[0];
48
- }));
49
-
50
- const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.entity_key]: curr.value_new }), {});
51
- // console.log('logChanges OK', type);
52
- return {
53
- change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
54
- };
55
- }
56
- catch (err) {
57
- console.error('logChanges error', type, table, id, data, err.toString());
58
- return {
59
- error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
60
- };
61
- }
62
- }
1
+ import getMeta from '../../../pg/funcs/getMeta.js';
2
+ import getTemplate from '../../..//table/funcs/getTemplate.js';
3
+ import { metaFormat } from '@opengis/fastify-table/utils.js';
4
+
5
+ const getValue = function (val) {
6
+ if (!val) return null;
7
+ return typeof val === 'object'
8
+ ? JSON.stringify(val)?.substring?.(0, 30)
9
+ : val?.toString?.()?.substring?.(0, 30);
10
+ }
11
+
12
+ export default async function logChanges({
13
+ pg, table, template, id, data, uid = 1, type,
14
+ }) {
15
+ if (!id) {
16
+ console.error('param id is required');
17
+ return null;
18
+ }
19
+ if (!table || !pg.pk?.[table]) {
20
+ console.error('table not found');
21
+ return null;
22
+ }
23
+ if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
24
+ console.error('log table not found');
25
+ return null;
26
+ }
27
+ if (!type) {
28
+ console.error('invalid type');
29
+ return null;
30
+ }
31
+
32
+ try {
33
+ const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
34
+ values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
35
+
36
+ const q = `select json_object_agg(entity_key, value_new) from (
37
+ select
38
+ entity_key,
39
+ value_new,
40
+ ( rank() over (partition by entity_key order by cdate desc) = 1 ) as is_latest
41
+ from log.table_changes_data
42
+
43
+ where change_id in (
44
+ select
45
+ change_id
46
+ from log.table_changes
47
+ where entity_id=$1
48
+ and entity_type=$2
49
+ )
50
+
51
+ )q where is_latest`;
52
+ // console.log(q, type, id);
53
+
54
+ const old = type !== 'INSERT' ? await pg.query(q, [id, table]).then(el => el.rows?.[0]?.json_object_agg || {}) : {};
55
+
56
+ const { columns = [] } = await getMeta({ table: 'log.table_changes_data' });
57
+ // const names = columns.map((el) => el.name);
58
+
59
+ const body = template ? await getTemplate('table', template) : null;
60
+ const cls = body?.columns?.filter(el => el.data)?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.data }), {});
61
+ Object.keys(data || {}).filter(key => typeof data[key] === 'boolean').forEach(key => Object.assign(cls, { [key]: 'yes_no' }));
62
+ const titles = (body?.columns || columns)?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.title || curr.ua }), {});
63
+
64
+ await metaFormat({ rows: [data], cls, sufix: false });
65
+ const newObj = Object.fromEntries(Object.entries(data || {}).map(el => ([[titles[el[0]] || el[0]], el[1]])));
66
+ const changesData = Object.keys(newObj || {}).map(el => ({
67
+ change_id: changeId,
68
+ entity_key: titles[el] || el,
69
+ value_old: getValue(old?.[el]),
70
+ value_new: getValue(newObj?.[el]),
71
+ uid,
72
+ })).filter(el => el?.value_new !== el?.value_old);
73
+
74
+ const res = await Promise.all(changesData.map(async (el) => {
75
+ const filterData = Object.entries(el);
76
+
77
+ const insertQuery = `insert into log.table_changes_data (${filterData?.map((key) => `"${key[0]}"`).join(',')})
78
+ values (${filterData?.map((key, i) => `$${i + 1}`).join(',')}) returning *`;
79
+
80
+ const { rows = [] } = await pg.query(insertQuery, [...filterData.map((el1) => (el1[1] && typeof el1[1] === 'object' && (!Array.isArray(el1[1]) || typeof el1[1]?.[0] === 'object') ? JSON.stringify(el1[1]) : el1[1]))]) || {};
81
+ return rows[0];
82
+ }));
83
+
84
+ const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.entity_key]: curr.value_new }), {});
85
+ // console.log('logChanges OK', type);
86
+ return {
87
+ change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
88
+ };
89
+ }
90
+ catch (err) {
91
+ console.error('logChanges error', type, table, id, data, err.toString());
92
+ return {
93
+ error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
94
+ };
95
+ }
96
+ }