@opengis/fastify-table 1.1.78 → 1.1.79

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 (77) hide show
  1. package/index.js +76 -76
  2. package/package.json +45 -45
  3. package/server/migrations/0.sql +80 -80
  4. package/server/migrations/cls.sql +39 -39
  5. package/server/migrations/context.sql +95 -0
  6. package/server/migrations/properties.sql +144 -144
  7. package/server/migrations/roles.sql +179 -175
  8. package/server/migrations/users.sql +170 -170
  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 +21 -21
  12. package/server/plugins/crud/funcs/dataInsert.js +38 -38
  13. package/server/plugins/crud/funcs/dataUpdate.js +50 -50
  14. package/server/plugins/crud/funcs/getAccess.js +48 -48
  15. package/server/plugins/crud/funcs/getOpt.js +13 -13
  16. package/server/plugins/crud/funcs/setOpt.js +21 -21
  17. package/server/plugins/crud/funcs/setToken.js +44 -44
  18. package/server/plugins/crud/funcs/utils/getFolder.js +10 -10
  19. package/server/plugins/crud/funcs/utils/logChanges.js +62 -62
  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/funcs/exec.migrations.js +79 -79
  25. package/server/plugins/migration/index.js +7 -7
  26. package/server/plugins/pg/funcs/getMeta.js +28 -28
  27. package/server/plugins/pg/funcs/getPG.js +33 -33
  28. package/server/plugins/pg/pgClients.js +21 -21
  29. package/server/plugins/policy/funcs/checkPolicy.js +92 -92
  30. package/server/plugins/policy/funcs/checkXSS.js +1 -1
  31. package/server/plugins/policy/index.js +12 -12
  32. package/server/plugins/policy/sqlInjection.js +33 -33
  33. package/server/plugins/redis/client.js +8 -8
  34. package/server/plugins/redis/funcs/redisClients.js +3 -3
  35. package/server/plugins/redis/index.js +17 -17
  36. package/server/plugins/table/funcs/addTemplateDir.js +8 -8
  37. package/server/plugins/table/funcs/getFilterSQL/index.js +96 -96
  38. package/server/plugins/table/funcs/getFilterSQL/util/formatValue.js +170 -170
  39. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  40. package/server/plugins/table/funcs/getFilterSQL/util/getFilterQuery.js +66 -66
  41. package/server/plugins/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  42. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  43. package/server/plugins/table/funcs/getSelect.js +19 -19
  44. package/server/plugins/table/funcs/getSelectMeta.js +60 -60
  45. package/server/plugins/table/funcs/getTemplates.js +19 -19
  46. package/server/plugins/table/funcs/gisIRColumn.js +72 -72
  47. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  48. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  49. package/server/plugins/table/funcs/metaFormat/getSelectVal.js +38 -22
  50. package/server/plugins/table/funcs/metaFormat/index.js +31 -30
  51. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  52. package/server/plugins/table/index.js +13 -13
  53. package/server/plugins/util/funcs/eventStream.js +28 -28
  54. package/server/plugins/util/index.js +7 -7
  55. package/server/routes/cron/index.js +14 -14
  56. package/server/routes/crud/controllers/deleteCrud.js +36 -36
  57. package/server/routes/crud/controllers/insert.js +80 -80
  58. package/server/routes/crud/controllers/table.js +91 -91
  59. package/server/routes/crud/controllers/update.js +82 -82
  60. package/server/routes/crud/index.js +21 -21
  61. package/server/routes/logger/controllers/logger.file.js +92 -92
  62. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  63. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  64. package/server/routes/logger/index.js +17 -17
  65. package/server/routes/properties/controllers/properties.add.js +55 -55
  66. package/server/routes/properties/controllers/properties.get.js +17 -17
  67. package/server/routes/properties/index.js +16 -16
  68. package/server/routes/table/controllers/data.js +144 -144
  69. package/server/routes/table/controllers/filter.js +60 -60
  70. package/server/routes/table/controllers/form.js +42 -42
  71. package/server/routes/table/controllers/search.js +74 -74
  72. package/server/routes/table/controllers/suggest.js +84 -84
  73. package/server/routes/table/index.js +28 -28
  74. package/server/routes/table/schema.js +64 -64
  75. package/server/routes/util/controllers/status.monitor.js +8 -8
  76. package/server/routes/util/index.js +11 -11
  77. package/utils.js +122 -122
@@ -1,21 +1,21 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
-
4
- // import { getPG, getMeta } from '../../../../utils.js';
5
-
6
- import logChanges from './utils/logChanges.js';
7
-
8
- export default async function dataDelete({
9
- table, id, pg: pg1, uid,
10
- }) {
11
- const pg = pg1 || getPG({ name: 'client' });
12
- const { pk } = await getMeta(table);
13
- if (!pg.tlist?.includes(table)) return 'table not exist';
14
- const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
15
- // console.log(updateDataset);
16
- const res = await pg.one(delQuery, [id]) || {};
17
- await logChanges({
18
- pg, table, id, uid, type: 'DELETE',
19
- });
20
- return res;
21
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ // import { getPG, getMeta } from '../../../../utils.js';
5
+
6
+ import logChanges from './utils/logChanges.js';
7
+
8
+ export default async function dataDelete({
9
+ table, id, pg: pg1, uid,
10
+ }) {
11
+ const pg = pg1 || getPG({ name: 'client' });
12
+ const { pk } = await getMeta(table);
13
+ if (!pg.tlist?.includes(table)) return 'table not exist';
14
+ const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
15
+ // console.log(updateDataset);
16
+ const res = await pg.one(delQuery, [id]) || {};
17
+ await logChanges({
18
+ pg, table, id, uid, type: 'DELETE',
19
+ });
20
+ return res;
21
+ }
@@ -1,38 +1,38 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
-
4
- // import { getPG, getMeta } from '../../../../utils.js';
5
-
6
- import logChanges from './utils/logChanges.js';
7
-
8
- export default async function dataInsert({
9
- table, data, pg: pg1, uid,
10
- }) {
11
- const pg = pg1 || getPG({ name: 'client' });
12
- if (!data) return null;
13
- const { columns } = await getMeta(table);
14
- if (!columns) return null;
15
-
16
- const names = columns.map((el) => el.name);
17
-
18
- Object.assign(data, { uid, editor_id: uid });
19
- const systemColumns = ['cdate', 'editor_date'].filter((el) => names.includes(el)).map((el) => [el, 'now()']);
20
-
21
- const filterData = Object.keys(data)
22
- .filter((el) => !['cdate', 'editor_date'].includes(el) && data[el] && names.includes(el)).map((el) => [el, data[el]]);
23
-
24
- const insertQuery = `insert into ${table}
25
-
26
- ( ${filterData?.map((key) => `"${key[0]}"`).concat(systemColumns.map((el) => el[0])).join(',')})
27
-
28
- 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(',')})
29
-
30
- returning *`;
31
-
32
- 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]))]) || {};
33
-
34
- await logChanges({
35
- pg, table, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
36
- });
37
- return res;
38
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ // import { getPG, getMeta } from '../../../../utils.js';
5
+
6
+ import logChanges from './utils/logChanges.js';
7
+
8
+ export default async function dataInsert({
9
+ table, data, pg: pg1, uid,
10
+ }) {
11
+ const pg = pg1 || getPG({ name: 'client' });
12
+ if (!data) return null;
13
+ const { columns } = await getMeta(table);
14
+ if (!columns) return null;
15
+
16
+ const names = columns.map((el) => el.name);
17
+
18
+ Object.assign(data, { uid, editor_id: uid });
19
+ const systemColumns = ['cdate', 'editor_date'].filter((el) => names.includes(el)).map((el) => [el, 'now()']);
20
+
21
+ const filterData = Object.keys(data)
22
+ .filter((el) => !['cdate', 'editor_date'].includes(el) && data[el] && names.includes(el)).map((el) => [el, data[el]]);
23
+
24
+ const insertQuery = `insert into ${table}
25
+
26
+ ( ${filterData?.map((key) => `"${key[0]}"`).concat(systemColumns.map((el) => el[0])).join(',')})
27
+
28
+ 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(',')})
29
+
30
+ returning *`;
31
+
32
+ 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]))]) || {};
33
+
34
+ await logChanges({
35
+ pg, table, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
36
+ });
37
+ return res;
38
+ }
@@ -1,50 +1,50 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
-
4
- // import { getPG, getMeta } from '../../../../utils.js';
5
-
6
- import logChanges from './utils/logChanges.js';
7
-
8
- const srids = {};
9
-
10
- export default async function dataUpdate({
11
- table, id, data, pg: pg1, uid,
12
- }) {
13
- if (!data || !table || !id) return null;
14
-
15
- const pg = pg1 || getPG({ name: 'client' });
16
- const { columns, pk } = await getMeta(table);
17
-
18
- const names = columns?.map((el) => el.name);
19
-
20
- const filterData = Object.keys(data)
21
- .filter((el) => (/* typeof data[el] === 'boolean' ? true : data[el] && */ names?.includes(el) && !['editor_date', 'editor_id'].includes(el)));
22
-
23
- const systemColumns = [['editor_date', 'now()'], ['editor_id', `'${uid.replace(/'/g, "''")}'`]].filter((el) => names.includes(el[0])).map((el) => `${el[0]} = ${el[1]}`).join(',');
24
-
25
- const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && el[1] && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
26
-
27
- // update geometry with srid
28
- if (!srids[table]) {
29
- const { srids1 } = await pg.query(`select json_object_agg(_table,rel) as srids1 from (
30
- select f_table_schema||'.'||f_table_name as _table,
31
- json_object_agg(f_geometry_column, case when srid = 0 then 4326 else srid end) as rel
32
- from public.geometry_columns group by f_table_schema||'.'||f_table_name
33
- )q`).then((res1) => res1.rows?.[0] || {});
34
- Object.assign(srids, srids1);
35
- }
36
-
37
- const updateQuery = `UPDATE ${table} SET ${systemColumns}, ${filterData
38
- ?.map((key, i) => (key?.includes('geom') && key !== 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),${srids[table]?.[key] || 4326})` : undefined)
39
- || (key === 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)` : `"${key}"=$${i + 2}`))
40
- .join(',')}
41
- WHERE ${pk} = $1 returning *`;
42
- // console.log(updateQuery, filterValue);
43
- const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
44
-
45
- await logChanges({
46
- pg, table, data, id, uid, type: 'UPDATE',
47
- });
48
-
49
- return res;
50
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ // import { getPG, getMeta } from '../../../../utils.js';
5
+
6
+ import logChanges from './utils/logChanges.js';
7
+
8
+ const srids = {};
9
+
10
+ export default async function dataUpdate({
11
+ table, id, data, pg: pg1, uid,
12
+ }) {
13
+ if (!data || !table || !id) return null;
14
+
15
+ const pg = pg1 || getPG({ name: 'client' });
16
+ const { columns, pk } = await getMeta(table);
17
+
18
+ const names = columns?.map((el) => el.name);
19
+
20
+ const filterData = Object.keys(data)
21
+ .filter((el) => (/* typeof data[el] === 'boolean' ? true : data[el] && */ names?.includes(el) && !['editor_date', 'editor_id'].includes(el)));
22
+
23
+ const systemColumns = [['editor_date', 'now()'], uid ? ['editor_id', `'${uid.replace(/'/g, "''")}'`] : []].filter((el) => names.includes(el[0])).map((el) => `${el[0]} = ${el[1]}`).join(',');
24
+
25
+ const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && el[1] && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
26
+
27
+ // update geometry with srid
28
+ if (!srids[table]) {
29
+ const { srids1 } = await pg.query(`select json_object_agg(_table,rel) as srids1 from (
30
+ select f_table_schema||'.'||f_table_name as _table,
31
+ json_object_agg(f_geometry_column, case when srid = 0 then 4326 else srid end) as rel
32
+ from public.geometry_columns group by f_table_schema||'.'||f_table_name
33
+ )q`).then((res1) => res1.rows?.[0] || {});
34
+ Object.assign(srids, srids1);
35
+ }
36
+
37
+ const updateQuery = `UPDATE ${table} SET ${systemColumns}, ${filterData
38
+ ?.map((key, i) => (key?.includes('geom') && key !== 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),${srids[table]?.[key] || 4326})` : undefined)
39
+ || (key === 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)` : `"${key}"=$${i + 2}`))
40
+ .join(',')}
41
+ WHERE ${pk} = $1 returning *`;
42
+ // console.log(updateQuery, filterValue);
43
+ const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
44
+
45
+ await logChanges({
46
+ pg, table, data, id, uid, type: 'UPDATE',
47
+ });
48
+
49
+ return res;
50
+ }
@@ -1,48 +1,48 @@
1
- import config from '../../../../config.js';
2
- import pgClients from '../../pg/pgClients.js';
3
-
4
- import getTemplate from '../../table/funcs/getTemplate.js';
5
- import applyHook from '../../hook/funcs/applyHook.js';
6
-
7
- // import { config, pgClients, getTemplate, applyHook } from '../../../../utils.js';
8
-
9
- const q = `select a.route_id as id, coalesce(b.actions,array['get']) as actions, b.scope
10
- from admin.routes a
11
- left join admin.role_access b on
12
- a.route_id=b.route_id
13
- left join admin.roles c on
14
- b.role_id=c.role_id
15
- and c.enabled
16
- left join admin.user_roles d on
17
- c.role_id=d.role_id
18
- and ( case when
19
- d.expiration is not null
20
- then d.expiration > CURRENT_DATE
21
- else 1=1
22
- end )
23
- where $1 in (a.route_id, a.alias) and $2 in (b.user_uid, d.user_uid)`;
24
-
25
- export default async function getAccess({ table, user = {} }) {
26
- if (!table) return null;
27
-
28
- const hookData = await applyHook('getAccess', { table, user });
29
- if (hookData) return hookData;
30
-
31
- const { uid } = user;
32
- const body = await getTemplate('table', table) || {};
33
-
34
- // console.log(user?.type);
35
- if (body.access === 'admin' && user?.type !== 'admin') return null;
36
-
37
- if (config.auth?.disable || user?.type === 'admin' || body?.public || body.access === 'public' || (body.access === 'user' && user.uid)) {
38
- return { actions: ['get'].concat(user.uid ? body.actions || body.action_default || [] : []), query: '1=1' };
39
- }
40
-
41
- if (!uid || !body?.table) return null;
42
-
43
- const { scope, actions = [] } = await pgClients.client.query(q, [table, uid]).then((res) => res.rows?.[0] || {});
44
-
45
- return {
46
- scope, actions, query: scope === 'my' ? `uid='${uid}` : null,
47
- };
48
- }
1
+ import config from '../../../../config.js';
2
+ import pgClients from '../../pg/pgClients.js';
3
+
4
+ import getTemplate from '../../table/funcs/getTemplate.js';
5
+ import applyHook from '../../hook/funcs/applyHook.js';
6
+
7
+ // import { config, pgClients, getTemplate, applyHook } from '../../../../utils.js';
8
+
9
+ const q = `select a.route_id as id, coalesce(b.actions,array['get']) as actions, b.scope
10
+ from admin.routes a
11
+ left join admin.role_access b on
12
+ a.route_id=b.route_id
13
+ left join admin.roles c on
14
+ b.role_id=c.role_id
15
+ and c.enabled
16
+ left join admin.user_roles d on
17
+ c.role_id=d.role_id
18
+ and ( case when
19
+ d.expiration is not null
20
+ then d.expiration > CURRENT_DATE
21
+ else 1=1
22
+ end )
23
+ where $1 in (a.route_id, a.alias) and $2 in (b.user_uid, d.user_uid)`;
24
+
25
+ export default async function getAccess({ table, user = {} }) {
26
+ if (!table) return null;
27
+
28
+ const hookData = await applyHook('getAccess', { table, user });
29
+ if (hookData) return hookData;
30
+
31
+ const { uid } = user;
32
+ const body = await getTemplate('table', table) || {};
33
+
34
+ // console.log(user?.type);
35
+ if (body.access === 'admin' && user?.type !== 'admin') return null;
36
+
37
+ if (config.auth?.disable || user?.type === 'admin' || body?.public || body.access === 'public' || (body.access === 'user' && user.uid)) {
38
+ return { actions: ['get'].concat(user.uid ? body.actions || body.action_default || [] : []), query: '1=1' };
39
+ }
40
+
41
+ if (!uid || !body?.table) return null;
42
+
43
+ const { scope, actions = [] } = await pgClients.client.query(q, [table, uid]).then((res) => res.rows?.[0] || {});
44
+
45
+ return {
46
+ scope, actions, query: scope === 'my' ? `uid='${uid}` : null,
47
+ };
48
+ }
@@ -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)).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)).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
+ }