@opengis/fastify-table 1.0.92 → 1.0.93

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 (53) hide show
  1. package/Changelog.md +281 -277
  2. package/crud/controllers/deleteCrud.js +22 -22
  3. package/crud/controllers/insert.js +58 -58
  4. package/crud/controllers/update.js +61 -61
  5. package/crud/funcs/dataDelete.js +19 -19
  6. package/crud/funcs/dataInsert.js +30 -30
  7. package/crud/funcs/getAccess.js +53 -53
  8. package/crud/funcs/getOpt.js +10 -10
  9. package/crud/funcs/setOpt.js +16 -16
  10. package/crud/funcs/utils/logChanges.js +71 -71
  11. package/crud/index.js +36 -36
  12. package/helper.js +28 -28
  13. package/index.js +97 -97
  14. package/notification/controllers/userNotifications.js +19 -19
  15. package/notification/funcs/addNotification.js +8 -8
  16. package/package.json +26 -26
  17. package/pg/pgClients.js +20 -20
  18. package/policy/funcs/checkPolicy.js +83 -83
  19. package/policy/funcs/sqlInjection.js +33 -33
  20. package/policy/index.js +14 -14
  21. package/redis/client.js +8 -8
  22. package/redis/funcs/redisClients.js +2 -2
  23. package/redis/index.js +19 -19
  24. package/server/migrations/0.sql +78 -78
  25. package/server/templates/form/test.dataset.form.json +411 -411
  26. package/server/templates/table/test.dataset.table.json +28 -28
  27. package/server/templates/table/test.gis.map.table.json +44 -44
  28. package/table/controllers/data.js +103 -103
  29. package/table/controllers/suggest.js +79 -79
  30. package/table/controllers/table.js +52 -52
  31. package/table/controllers/utils/getSelectMeta.js +66 -66
  32. package/table/controllers/utils/getTemplate.js +28 -28
  33. package/table/controllers/utils/gisIRColumn.js +68 -68
  34. package/table/funcs/getFilterSQL/index.js +79 -75
  35. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  36. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  37. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  38. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  39. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  40. package/table/funcs/metaFormat/getSelectVal.js +20 -20
  41. package/table/funcs/metaFormat/index.js +28 -28
  42. package/test/api/crud.test.js +88 -88
  43. package/test/api/table.test.js +89 -89
  44. package/test/api/widget.test.js +117 -117
  45. package/test/funcs/crud.test.js +122 -122
  46. package/util/controllers/properties.add.js +57 -57
  47. package/util/controllers/status.monitor.js +8 -8
  48. package/widget/controllers/utils/historyFormat.js +76 -76
  49. package/widget/controllers/utils/obj2db.js +13 -13
  50. package/widget/controllers/widget.del.js +44 -44
  51. package/widget/controllers/widget.get.js +98 -98
  52. package/widget/controllers/widget.set.js +76 -76
  53. package/widget/index.js +40 -40
@@ -1,58 +1,58 @@
1
- import dataInsert from '../funcs/dataInsert.js';
2
- import getToken from '../funcs/getToken.js';
3
- import checkXSS from './utils/checkXSS.js';
4
- import getTemplate from '../../table/controllers/utils/getTemplate.js';
5
- import getAccess from '../funcs/getAccess.js';
6
-
7
- export default async function insert(req) {
8
- const { actions = [] } = await getAccess(req, req.params.table) || {};
9
- if (!actions.includes('edit')) {
10
- return { message: 'access restricted', status: 403 };
11
- }
12
- if (!req.params?.table) {
13
- return { message: 'table is required', status: 400 };
14
- }
15
- const loadTemplate = await getTemplate('table', req.params.table);
16
- const { table, public: ispublic } = loadTemplate || req.params || {};
17
- if (!table) {
18
- return { message: 'table not found', status: 404 };
19
- }
20
-
21
- const { funcs = {}, user = {}, params = {} } = req;
22
- const tokenDataString = await getToken({
23
- funcs, uid: user.uid, token: params.table, mode: 'a', json: 0,
24
- });
25
-
26
- const { form, add } = JSON.parse(tokenDataString || '{}');
27
-
28
- const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
29
-
30
- const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
31
-
32
- if (xssCheck.error && formData?.xssCheck !== false) {
33
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
34
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
35
- }
36
-
37
- const { uid } = funcs.config?.auth?.disable || ispublic ? { uid: '1' } : user || {};
38
- Object.assign(req.body, { uid, editor_id: uid });
39
- const res = await dataInsert({
40
- table: add || table, data: req.body, uid,
41
- });
42
-
43
- const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
44
- if (extraKeys?.length) {
45
- res.extra = {};
46
- await Promise.all(extraKeys?.map(async (key) => {
47
- const extraRows = await Promise.all(req.body[key].map(async (row) => {
48
- const extraRes = await dataInsert({
49
- table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] }, uid,
50
- });
51
- return extraRes?.rows?.[0];
52
- }));
53
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
54
- }));
55
- }
56
-
57
- return { rows: res.rows, extra: res.extra };
58
- }
1
+ import dataInsert from '../funcs/dataInsert.js';
2
+ import getToken from '../funcs/getToken.js';
3
+ import checkXSS from './utils/checkXSS.js';
4
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
5
+ import getAccess from '../funcs/getAccess.js';
6
+
7
+ export default async function insert(req) {
8
+ const { actions = [] } = await getAccess(req, req.params.table) || {};
9
+ if (!actions.includes('edit')) {
10
+ return { message: 'access restricted', status: 403 };
11
+ }
12
+ if (!req.params?.table) {
13
+ return { message: 'table is required', status: 400 };
14
+ }
15
+ const loadTemplate = await getTemplate('table', req.params.table);
16
+ const { table, public: ispublic } = loadTemplate || req.params || {};
17
+ if (!table) {
18
+ return { message: 'table not found', status: 404 };
19
+ }
20
+
21
+ const { funcs = {}, user = {}, params = {} } = req;
22
+ const tokenDataString = await getToken({
23
+ funcs, uid: user.uid, token: params.table, mode: 'a', json: 0,
24
+ });
25
+
26
+ const { form, add } = JSON.parse(tokenDataString || '{}');
27
+
28
+ const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
29
+
30
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
31
+
32
+ if (xssCheck.error && formData?.xssCheck !== false) {
33
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
34
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
35
+ }
36
+
37
+ const { uid } = funcs.config?.auth?.disable || ispublic ? { uid: '1' } : user || {};
38
+ Object.assign(req.body, { uid, editor_id: uid });
39
+ const res = await dataInsert({
40
+ table: add || table, data: req.body, uid,
41
+ });
42
+
43
+ const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
44
+ if (extraKeys?.length) {
45
+ res.extra = {};
46
+ await Promise.all(extraKeys?.map(async (key) => {
47
+ const extraRows = await Promise.all(req.body[key].map(async (row) => {
48
+ const extraRes = await dataInsert({
49
+ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] }, uid,
50
+ });
51
+ return extraRes?.rows?.[0];
52
+ }));
53
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
54
+ }));
55
+ }
56
+
57
+ return { rows: res.rows, extra: res.extra };
58
+ }
@@ -1,61 +1,61 @@
1
- import dataUpdate from '../funcs/dataUpdate.js';
2
- import dataInsert from '../funcs/dataInsert.js';
3
- import pgClients from '../../pg/pgClients.js';
4
- import getToken from '../funcs/getToken.js';
5
- import checkXSS from './utils/checkXSS.js';
6
- import getTemplate from '../../table/controllers/utils/getTemplate.js';
7
- import getAccess from '../funcs/getAccess.js';
8
-
9
- export default async function update(req) {
10
- const { actions = [], scope, my } = await getAccess(req, req.params.table, req.params.id) || {};
11
- if (!actions.includes('edit') || (scope === 'my' && !my)) {
12
- return { message: 'access restricted', status: 403 };
13
- }
14
- if (!req.params?.table) {
15
- return { message: 'table is required', status: 400 };
16
- }
17
- if (!req.params?.id) {
18
- return { message: 'id is required', status: 404 };
19
- }
20
- const loadTemplate = await getTemplate('table', req.params.table);
21
- const { table, public: ispublic } = loadTemplate || req.params || {};
22
- const { id } = req.params || {};
23
-
24
- const { funcs = {}, user = {}, params = {} } = req;
25
- const uid = funcs.config?.auth?.disable || ispublic ? '1' : user.uid;
26
- const tokenDataString = await getToken({
27
- funcs, uid, token: params.table, mode: 'w', json: 0,
28
- });
29
-
30
- const tokenData = JSON.parse(tokenDataString || '{}');
31
-
32
- const formData = tokenData?.form || loadTemplate?.form ? await getTemplate('form', tokenData.form || loadTemplate?.form) : {};
33
-
34
- const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
35
-
36
- if (xssCheck.error && formData?.xssCheck !== false) {
37
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
38
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
39
- }
40
-
41
- const res = await dataUpdate({
42
- table: tokenData?.table || table, id: tokenData?.id || id, data: req.body, uid,
43
- });
44
-
45
- const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
46
- if (extraKeys?.length) {
47
- res.extra = {};
48
- await Promise.all(extraKeys?.map(async (key) => {
49
- // delete old extra data
50
- await pgClients.client.query(`delete from ${formData[key].table} where ${formData[key].parent_id}=$1`, [req.body[formData[key].parent_id]]); // rewrite?
51
- // insert new extra data
52
- const extraRows = await Promise.all(req.body[key].map(async (row) => {
53
- const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] }, uid });
54
- return extraRes?.rows?.[0];
55
- }));
56
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
57
- }));
58
- }
59
-
60
- return res;
61
- }
1
+ import dataUpdate from '../funcs/dataUpdate.js';
2
+ import dataInsert from '../funcs/dataInsert.js';
3
+ import pgClients from '../../pg/pgClients.js';
4
+ import getToken from '../funcs/getToken.js';
5
+ import checkXSS from './utils/checkXSS.js';
6
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
7
+ import getAccess from '../funcs/getAccess.js';
8
+
9
+ export default async function update(req) {
10
+ const { actions = [], scope, my } = await getAccess(req, req.params.table, req.params.id) || {};
11
+ if (!actions.includes('edit') || (scope === 'my' && !my)) {
12
+ return { message: 'access restricted', status: 403 };
13
+ }
14
+ if (!req.params?.table) {
15
+ return { message: 'table is required', status: 400 };
16
+ }
17
+ if (!req.params?.id) {
18
+ return { message: 'id is required', status: 404 };
19
+ }
20
+ const loadTemplate = await getTemplate('table', req.params.table);
21
+ const { table, public: ispublic } = loadTemplate || req.params || {};
22
+ const { id } = req.params || {};
23
+
24
+ const { funcs = {}, user = {}, params = {} } = req;
25
+ const uid = funcs.config?.auth?.disable || ispublic ? '1' : user.uid;
26
+ const tokenDataString = await getToken({
27
+ funcs, uid, token: params.table, mode: 'w', json: 0,
28
+ });
29
+
30
+ const tokenData = JSON.parse(tokenDataString || '{}');
31
+
32
+ const formData = tokenData?.form || loadTemplate?.form ? await getTemplate('form', tokenData.form || loadTemplate?.form) : {};
33
+
34
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
35
+
36
+ if (xssCheck.error && formData?.xssCheck !== false) {
37
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
38
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
39
+ }
40
+
41
+ const res = await dataUpdate({
42
+ table: tokenData?.table || table, id: tokenData?.id || id, data: req.body, uid,
43
+ });
44
+
45
+ const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
46
+ if (extraKeys?.length) {
47
+ res.extra = {};
48
+ await Promise.all(extraKeys?.map(async (key) => {
49
+ // delete old extra data
50
+ await pgClients.client.query(`delete from ${formData[key].table} where ${formData[key].parent_id}=$1`, [req.body[formData[key].parent_id]]); // rewrite?
51
+ // insert new extra data
52
+ const extraRows = await Promise.all(req.body[key].map(async (row) => {
53
+ const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] }, uid });
54
+ return extraRes?.rows?.[0];
55
+ }));
56
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
57
+ }));
58
+ }
59
+
60
+ return res;
61
+ }
@@ -1,19 +1,19 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
-
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
- import logChanges from './utils/logChanges.js';
5
-
6
- export default async function dataDelete({
7
- table, id, pg: pg1, uid,
8
- }) {
9
- const pg = pg1 || getPG({ name: 'client' });
10
- const { pk } = await getMeta(table);
11
- if (!pg.tlist?.includes(table)) return 'table not exist';
12
- const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
13
- // console.log(updateDataset);
14
- const res = await pg.one(delQuery, [id]) || {};
15
- await logChanges({
16
- pg, table, id, uid, type: 'DELETE',
17
- });
18
- return res;
19
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+ import logChanges from './utils/logChanges.js';
5
+
6
+ export default async function dataDelete({
7
+ table, id, pg: pg1, uid,
8
+ }) {
9
+ const pg = pg1 || getPG({ name: 'client' });
10
+ const { pk } = await getMeta(table);
11
+ if (!pg.tlist?.includes(table)) return 'table not exist';
12
+ const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
13
+ // console.log(updateDataset);
14
+ const res = await pg.one(delQuery, [id]) || {};
15
+ await logChanges({
16
+ pg, table, id, uid, type: 'DELETE',
17
+ });
18
+ return res;
19
+ }
@@ -1,30 +1,30 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
- import logChanges from './utils/logChanges.js';
4
-
5
- export default async function dataInsert({
6
- table, data, pg: pg1, uid,
7
- }) {
8
- const pg = pg1 || getPG({ name: 'client' });
9
- if (!data) return null;
10
- const { columns } = await getMeta(table);
11
- if (!columns) return null;
12
-
13
- const names = columns.map((el) => el.name);
14
- const filterData = Object.keys(data)
15
- .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
16
-
17
- const insertQuery = `insert into ${table}
18
-
19
- ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
20
-
21
- values (${filterData?.map((key, i) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).join(',')})
22
-
23
- returning *`;
24
-
25
- 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]))]) || {};
26
- await logChanges({
27
- pg, table, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
28
- });
29
- return res;
30
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+ import logChanges from './utils/logChanges.js';
4
+
5
+ export default async function dataInsert({
6
+ table, data, pg: pg1, uid,
7
+ }) {
8
+ const pg = pg1 || getPG({ name: 'client' });
9
+ if (!data) return null;
10
+ const { columns } = await getMeta(table);
11
+ if (!columns) return null;
12
+
13
+ const names = columns.map((el) => el.name);
14
+ const filterData = Object.keys(data)
15
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
16
+
17
+ const insertQuery = `insert into ${table}
18
+
19
+ ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
20
+
21
+ values (${filterData?.map((key, i) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).join(',')})
22
+
23
+ returning *`;
24
+
25
+ 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]))]) || {};
26
+ await logChanges({
27
+ pg, table, data, id: res.rows?.[0]?.[pg.pk[table]], uid, type: 'INSERT',
28
+ });
29
+ return res;
30
+ }
@@ -1,53 +1,53 @@
1
- import getMeta from '../../pg/funcs/getMeta.js';
2
- import getTemplate from '../../table/controllers/utils/getTemplate.js';
3
- import config from '../../config.js';
4
-
5
- const q = `select a.route_id as id, b.actions, b.scope
6
- from admin.routes a
7
- left join admin.access b on
8
- a.route_id=b.route_id
9
- left join admin.roles c on
10
- b.role_id=c.role_id
11
- and c.enabled
12
- left join admin.user_roles d on
13
- c.role_id=d.role_id
14
- and ( case when
15
- d.expiration is not null
16
- then d.expiration > CURRENT_DATE
17
- else 1=1
18
- end )
19
- where a.route_id=$1 and $2 in (b.user_uid, d.user_uid)`;
20
-
21
- export default async function getAccess(req, template, id = null) {
22
- if (config.disableAccessRestriction || true) {
23
- return { actions: ['get', 'edit', 'del'], my: true, query: '1=1' };
24
- }
25
- const { pg, session = {} } = req;
26
- const { uid, user_type: userType } = session.passport?.user || {};
27
- if (!uid || !template) return null;
28
-
29
- if (!pg.pk?.['admin.access']) return null;
30
-
31
- const { table } = await getTemplate('table', template) || {};
32
- if (!table) return null;
33
-
34
- const { scope = 'my', actions = [] } = await pg.one(q, [template, uid]);
35
- // console.log(scope, actions);
36
-
37
- const { columns = [] } = await getMeta(table);
38
- const columnList = columns.map((el) => el.name || el).join(',');
39
-
40
- const query = userType?.includes('admin') ? '1=1' : {
41
- my: `uid='${uid}'`,
42
- responsible: columnList.includes('responsible_id')
43
- ? `responsible_id='${uid}'`
44
- : `uid='${uid}'`,
45
- all: '1=1',
46
- }[scope];
47
-
48
- const { my } = pg.pk?.[table] && id ? await pg.one(`select uid=$1 as my from ${table} where ${pg.pk?.[table]}=$2`, [uid, id]) : {};
49
-
50
- return {
51
- scope, actions, query, my,
52
- };
53
- }
1
+ import getMeta from '../../pg/funcs/getMeta.js';
2
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
3
+ import config from '../../config.js';
4
+
5
+ const q = `select a.route_id as id, b.actions, b.scope
6
+ from admin.routes a
7
+ left join admin.access b on
8
+ a.route_id=b.route_id
9
+ left join admin.roles c on
10
+ b.role_id=c.role_id
11
+ and c.enabled
12
+ left join admin.user_roles d on
13
+ c.role_id=d.role_id
14
+ and ( case when
15
+ d.expiration is not null
16
+ then d.expiration > CURRENT_DATE
17
+ else 1=1
18
+ end )
19
+ where a.route_id=$1 and $2 in (b.user_uid, d.user_uid)`;
20
+
21
+ export default async function getAccess(req, template, id = null) {
22
+ if (config.disableAccessRestriction || true) {
23
+ return { actions: ['get', 'edit', 'del'], my: true, query: '1=1' };
24
+ }
25
+ const { pg, session = {} } = req;
26
+ const { uid, user_type: userType } = session.passport?.user || {};
27
+ if (!uid || !template) return null;
28
+
29
+ if (!pg.pk?.['admin.access']) return null;
30
+
31
+ const { table } = await getTemplate('table', template) || {};
32
+ if (!table) return null;
33
+
34
+ const { scope = 'my', actions = [] } = await pg.one(q, [template, uid]);
35
+ // console.log(scope, actions);
36
+
37
+ const { columns = [] } = await getMeta(table);
38
+ const columnList = columns.map((el) => el.name || el).join(',');
39
+
40
+ const query = userType?.includes('admin') ? '1=1' : {
41
+ my: `uid='${uid}'`,
42
+ responsible: columnList.includes('responsible_id')
43
+ ? `responsible_id='${uid}'`
44
+ : `uid='${uid}'`,
45
+ all: '1=1',
46
+ }[scope];
47
+
48
+ const { my } = pg.pk?.[table] && id ? await pg.one(`select uid=$1 as my from ${table} where ${pg.pk?.[table]}=$2`, [uid, id]) : {};
49
+
50
+ return {
51
+ scope, actions, query, my,
52
+ };
53
+ }
@@ -1,10 +1,10 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
-
3
- export default async function getOpt(token, funcs) {
4
- const rclient = getRedis({ db: 0, funcs });
5
-
6
- const key = `opt:${token}`;
7
- const data = await rclient.get(key);
8
- if (!data) return null;
9
- return JSON.parse(data);
10
- }
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+
3
+ export default async function getOpt(token, funcs) {
4
+ const rclient = getRedis({ db: 0, funcs });
5
+
6
+ const key = `opt:${token}`;
7
+ const data = await rclient.get(key);
8
+ if (!data) return null;
9
+ return JSON.parse(data);
10
+ }
@@ -1,16 +1,16 @@
1
- import { createHash } from 'crypto';
2
- import getRedis from '../../redis/funcs/getRedis.js';
3
-
4
- function md5(string) {
5
- return createHash('md5').update(string).digest('hex');
6
- }
7
-
8
- export default async function setOpt(params) {
9
- const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params), 'hex').toString('base64').replace(/[+-=]+/g, '');
10
- // const token = md5(params);
11
- const key = `opt:${token}`;
12
-
13
- const rclient = getRedis({ db: 0, funcs: params.funcs });
14
- await rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
15
- return token;
16
- }
1
+ import { createHash } from 'crypto';
2
+ import getRedis from '../../redis/funcs/getRedis.js';
3
+
4
+ function md5(string) {
5
+ return createHash('md5').update(string).digest('hex');
6
+ }
7
+
8
+ export default async function setOpt(params) {
9
+ const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params), 'hex').toString('base64').replace(/[+-=]+/g, '');
10
+ // const token = md5(params);
11
+ const key = `opt:${token}`;
12
+
13
+ const rclient = getRedis({ db: 0, funcs: params.funcs });
14
+ await rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
15
+ return token;
16
+ }
@@ -1,71 +1,71 @@
1
- function formatData(fieldType = 'text', value = null) {
2
- if (!value) return null;
3
- if (fieldType === 'geometry') {
4
- return typeof value === 'object' ? `st_astext(st_geomfromgeojson('${JSON.stringify(value)}'::json))` : `st_astext('${value}'::geometry)`;
5
- }
6
- if (['integer', 'numeric', 'double precision'].includes(fieldType)) {
7
- return value || null;
8
- }
9
- if (fieldType.includes('timestamp') || fieldType === 'date') {
10
- if (typeof value === 'object') {
11
- return value ? `'${value.toISOString()}'::${fieldType}` : null;
12
- }
13
- return value ? `'${value}'::${fieldType}` : null;
14
- }
15
- /* if (fieldType.includes('json') && Array.isArray(value)) {
16
- return value;
17
- } */
18
- if (Array.isArray(value)) {
19
- return `'{ ${value.join(',')} }'::${fieldType}`;
20
- }
21
- return typeof value === 'object' ? JSON.stringify(value) : `'${value || null}'`;
22
- }
23
-
24
- export default async function logChanges({
25
- pg, table, id, data, uid = 1, type,
26
- }) {
27
- if (!id) {
28
- console.error('param id is required');
29
- return null;
30
- }
31
- if (!table || !pg.pk?.[table]) {
32
- console.error('table not found');
33
- return null;
34
- }
35
- if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
36
- console.error('log table not found');
37
- return null;
38
- }
39
- if (!type) {
40
- console.error('invalid type');
41
- return null;
42
- }
43
-
44
- try {
45
- const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
46
- values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
47
-
48
- const q = `select ${Object.keys(data || {}).join(',') || '*'} from ${table} where ${pg.pk?.[table]}=$1`;
49
- // console.log(q, type, id);
50
- const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
51
- const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
52
-
53
- const fieldTypes = fields?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: pg.pgType[curr.dataTypeID] }), {}) || {};
54
- const q1 = Object.keys(data || {}).map((el) => `insert into log.table_changes_data(change_id,entity_key,value_old,value_new)
55
- values('${changeId}', '${el}', ${formatData(fieldTypes[el], old[el])}, ${formatData(fieldTypes[el], data[el])}) returning *`).join(';\n');
56
- // console.log(q1);
57
- const res = await pg.query(q1);
58
-
59
- const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.rows?.[0].entity_key]: curr.rows?.[0].value_new }), {});
60
- // console.log('logChanges OK', type);
61
- return {
62
- change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
63
- };
64
- }
65
- catch (err) {
66
- console.error('logChanges error', type, table, id, data, err.toString());
67
- return {
68
- error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
69
- };
70
- }
71
- }
1
+ function formatData(fieldType = 'text', value = null) {
2
+ if (!value) return null;
3
+ if (fieldType === 'geometry') {
4
+ return typeof value === 'object' ? `st_astext(st_geomfromgeojson('${JSON.stringify(value)}'::json))` : `st_astext('${value}'::geometry)`;
5
+ }
6
+ if (['integer', 'numeric', 'double precision'].includes(fieldType)) {
7
+ return value || null;
8
+ }
9
+ if (fieldType.includes('timestamp') || fieldType === 'date') {
10
+ if (typeof value === 'object') {
11
+ return value ? `'${value.toISOString()}'::${fieldType}` : null;
12
+ }
13
+ return value ? `'${value}'::${fieldType}` : null;
14
+ }
15
+ /* if (fieldType.includes('json') && Array.isArray(value)) {
16
+ return value;
17
+ } */
18
+ if (Array.isArray(value)) {
19
+ return `'{ ${value.join(',')} }'::${fieldType}`;
20
+ }
21
+ return typeof value === 'object' ? JSON.stringify(value) : `'${value || null}'`;
22
+ }
23
+
24
+ export default async function logChanges({
25
+ pg, table, id, data, uid = 1, type,
26
+ }) {
27
+ if (!id) {
28
+ console.error('param id is required');
29
+ return null;
30
+ }
31
+ if (!table || !pg.pk?.[table]) {
32
+ console.error('table not found');
33
+ return null;
34
+ }
35
+ if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
36
+ console.error('log table not found');
37
+ return null;
38
+ }
39
+ if (!type) {
40
+ console.error('invalid type');
41
+ return null;
42
+ }
43
+
44
+ try {
45
+ const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
46
+ values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
47
+
48
+ const q = `select ${Object.keys(data || {}).join(',') || '*'} from ${table} where ${pg.pk?.[table]}=$1`;
49
+ // console.log(q, type, id);
50
+ const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
51
+ const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
52
+
53
+ const fieldTypes = fields?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: pg.pgType[curr.dataTypeID] }), {}) || {};
54
+ const q1 = Object.keys(data || {}).map((el) => `insert into log.table_changes_data(change_id,entity_key,value_old,value_new)
55
+ values('${changeId}', '${el}', ${formatData(fieldTypes[el], old[el])}, ${formatData(fieldTypes[el], data[el])}) returning *`).join(';\n');
56
+ // console.log(q1);
57
+ const res = await pg.query(q1);
58
+
59
+ const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.rows?.[0].entity_key]: curr.rows?.[0].value_new }), {});
60
+ // console.log('logChanges OK', type);
61
+ return {
62
+ change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
63
+ };
64
+ }
65
+ catch (err) {
66
+ console.error('logChanges error', type, table, id, data, err.toString());
67
+ return {
68
+ error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
69
+ };
70
+ }
71
+ }