@opengis/fastify-table 1.1.131 → 1.1.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +86 -86
  2. package/index.js +78 -78
  3. package/package.json +1 -1
  4. package/server/migrations/0.sql +80 -80
  5. package/server/migrations/cls.sql +39 -39
  6. package/server/migrations/context.sql +94 -94
  7. package/server/migrations/properties.sql +144 -144
  8. package/server/migrations/users.sql +173 -173
  9. package/server/plugins/cron/funcs/addCron.js +130 -130
  10. package/server/plugins/cron/index.js +6 -6
  11. package/server/plugins/crud/funcs/dataDelete.js +23 -23
  12. package/server/plugins/crud/funcs/dataInsert.js +45 -45
  13. package/server/plugins/crud/funcs/dataUpdate.js +65 -65
  14. package/server/plugins/crud/funcs/getOpt.js +13 -13
  15. package/server/plugins/crud/funcs/setOpt.js +21 -21
  16. package/server/plugins/crud/funcs/setToken.js +44 -44
  17. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  18. package/server/plugins/crud/funcs/utils/logChanges.js +62 -62
  19. package/server/plugins/crud/index.js +23 -23
  20. package/server/plugins/hook/index.js +8 -8
  21. package/server/plugins/logger/errorStatus.js +19 -19
  22. package/server/plugins/logger/index.js +21 -21
  23. package/server/plugins/migration/funcs/exec.migrations.js +86 -86
  24. package/server/plugins/migration/index.js +7 -7
  25. package/server/plugins/pg/funcs/getPG.js +33 -33
  26. package/server/plugins/pg/pgClients.js +21 -21
  27. package/server/plugins/policy/index.js +12 -12
  28. package/server/plugins/policy/sqlInjection.js +33 -33
  29. package/server/plugins/redis/client.js +8 -8
  30. package/server/plugins/redis/funcs/redisClients.js +3 -3
  31. package/server/plugins/redis/index.js +17 -17
  32. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  33. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  34. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +171 -170
  35. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  36. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  37. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  38. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  39. package/server/plugins/table/funcs/getSelect.js +29 -29
  40. package/server/plugins/table/funcs/getTemplates.js +19 -19
  41. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  42. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  43. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  44. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +50 -50
  45. package/server/plugins/table/funcs/metaFormat/index.js +45 -45
  46. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  47. package/server/plugins/table/index.js +13 -13
  48. package/server/plugins/util/funcs/eventStream.js +28 -28
  49. package/server/plugins/util/index.js +7 -7
  50. package/server/routes/cron/index.js +14 -14
  51. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  52. package/server/routes/crud/controllers/insert.js +83 -83
  53. package/server/routes/crud/controllers/table.js +91 -91
  54. package/server/routes/crud/controllers/update.js +91 -91
  55. package/server/routes/logger/controllers/logger.file.js +92 -92
  56. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  57. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  58. package/server/routes/logger/index.js +17 -17
  59. package/server/routes/properties/controllers/properties.add.js +55 -55
  60. package/server/routes/properties/controllers/properties.get.js +17 -17
  61. package/server/routes/properties/index.js +16 -16
  62. package/server/routes/table/controllers/data.js +156 -156
  63. package/server/routes/table/controllers/filter.js +66 -66
  64. package/server/routes/table/controllers/form.js +42 -42
  65. package/server/routes/table/controllers/search.js +74 -74
  66. package/server/routes/table/controllers/suggest.js +158 -122
  67. package/server/routes/table/index.js +29 -29
  68. package/server/routes/table/schema.js +64 -64
  69. package/server/routes/util/controllers/status.monitor.js +8 -8
  70. package/server/routes/util/index.js +11 -11
  71. package/utils.js +122 -122
@@ -1,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, 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,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, 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,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, 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,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,62 @@
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
+
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,23 +1,23 @@
1
- // import getOpt from './funcs/getOpt.js';
2
- // import setOpt from './funcs/setOpt.js';
3
-
4
- // import isFileExists from './funcs/isFileExists.js';
5
-
6
- // import dataUpdate from './funcs/dataUpdate.js';
7
- // import dataInsert from './funcs/dataInsert.js';
8
-
9
- // import getAccessFunc from './funcs/getAccess.js';
10
-
11
- async function plugin(fastify) {
12
- // fastify.decorate('setOpt', setOpt);
13
- // fastify.decorate('getOpt', getOpt);
14
-
15
- // fastify.decorate('dataUpdate', dataUpdate);
16
- // fastify.decorate('dataInsert', dataInsert);
17
-
18
- // fastify.decorate('getAccess', getAccessFunc);
19
-
20
- // fastify.decorate('isFileExists', isFileExists);
21
- }
22
-
23
- export default plugin;
1
+ // import getOpt from './funcs/getOpt.js';
2
+ // import setOpt from './funcs/setOpt.js';
3
+
4
+ // import isFileExists from './funcs/isFileExists.js';
5
+
6
+ // import dataUpdate from './funcs/dataUpdate.js';
7
+ // import dataInsert from './funcs/dataInsert.js';
8
+
9
+ // import getAccessFunc from './funcs/getAccess.js';
10
+
11
+ async function plugin(fastify) {
12
+ // fastify.decorate('setOpt', setOpt);
13
+ // fastify.decorate('getOpt', getOpt);
14
+
15
+ // fastify.decorate('dataUpdate', dataUpdate);
16
+ // fastify.decorate('dataInsert', dataInsert);
17
+
18
+ // fastify.decorate('getAccess', getAccessFunc);
19
+
20
+ // fastify.decorate('isFileExists', isFileExists);
21
+ }
22
+
23
+ export default plugin;
@@ -1,8 +1,8 @@
1
- import addHook from './funcs/addHook.js';
2
- import applyHook from './funcs/applyHook.js';
3
-
4
- async function plugin(fastify) {
5
- // fastify.decorate('addHook', addHook);
6
- // fastify.decorate('applyHook', applyHook);
7
- }
8
- export default plugin;
1
+ import addHook from './funcs/addHook.js';
2
+ import applyHook from './funcs/applyHook.js';
3
+
4
+ async function plugin(fastify) {
5
+ // fastify.decorate('addHook', addHook);
6
+ // fastify.decorate('applyHook', applyHook);
7
+ }
8
+ export default plugin;