@opengis/fastify-table 1.0.82 → 1.0.84

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 (65) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +253 -245
  3. package/README.md +26 -26
  4. package/config.js +10 -10
  5. package/cron/controllers/cronApi.js +22 -22
  6. package/cron/controllers/utils/cronList.js +1 -1
  7. package/cron/funcs/addCron.js +131 -131
  8. package/cron/index.js +10 -10
  9. package/crud/controllers/utils/checkXSS.js +45 -45
  10. package/crud/controllers/utils/xssInjection.js +72 -72
  11. package/crud/funcs/dataDelete.js +15 -15
  12. package/crud/funcs/dataUpdate.js +24 -24
  13. package/crud/funcs/getToken.js +27 -27
  14. package/crud/funcs/isFileExists.js +13 -13
  15. package/crud/funcs/setToken.js +53 -53
  16. package/crud/index.js +36 -36
  17. package/index.js +1 -1
  18. package/migration/exec.migrations.js +75 -75
  19. package/notification/controllers/testEmail.js +49 -49
  20. package/notification/funcs/sendNotification.js +111 -111
  21. package/notification/funcs/utils/sendEmail.js +39 -39
  22. package/notification/index.js +38 -38
  23. package/package.json +26 -26
  24. package/pg/funcs/getPG.js +30 -30
  25. package/redis/funcs/getRedis.js +23 -23
  26. package/server/migrations/0.sql +14 -0
  27. package/server/migrations/crm.sql +150 -150
  28. package/server/migrations/log.sql +43 -43
  29. package/server/templates/select/test.storage.data.json +3 -3
  30. package/server/templates/select/test.suggest.ato_new.json +2 -2
  31. package/server/templates/select/test.suggest.ato_new.sql +25 -25
  32. package/server/templates/select/test.suggest.data.json +4 -4
  33. package/server/templates/select/test.suggest.parent.sql +2 -2
  34. package/server.js +14 -14
  35. package/table/controllers/card.js +44 -44
  36. package/table/controllers/data.js +97 -97
  37. package/table/controllers/filter.js +37 -37
  38. package/table/controllers/form.js +28 -28
  39. package/table/controllers/search.js +72 -72
  40. package/table/controllers/suggest.js +18 -1
  41. package/table/controllers/utils/getSelect.js +20 -20
  42. package/table/controllers/utils/getSelectMeta.js +66 -66
  43. package/table/controllers/utils/getTemplate.js +28 -28
  44. package/table/controllers/utils/getTemplates.js +18 -18
  45. package/table/funcs/metaFormat/index.js +27 -27
  46. package/table/index.js +80 -78
  47. package/test/api/crud.xss.test.js +72 -72
  48. package/test/api/notification.test.js +37 -37
  49. package/test/api/suggest.test.js +65 -65
  50. package/test/api/table.test.js +57 -57
  51. package/test/api/widget.test.js +114 -114
  52. package/test/config.example +18 -18
  53. package/test/funcs/crud.test.js +76 -76
  54. package/test/funcs/notification.test.js +31 -31
  55. package/test/funcs/pg.test.js +34 -34
  56. package/test/funcs/redis.test.js +19 -19
  57. package/test/templates/cls/test.json +9 -9
  58. package/test/templates/form/cp_building.form.json +32 -32
  59. package/test/templates/select/account_id.json +3 -3
  60. package/test/templates/select/storage.data.json +2 -2
  61. package/test/templates/table/gis.dataset.table.json +20 -20
  62. package/util/controllers/next.id.js +4 -4
  63. package/util/controllers/properties.add.js +50 -50
  64. package/util/controllers/properties.get.js +19 -19
  65. package/widget/index.js +40 -40
@@ -1,27 +1,27 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
- import config from '../../config.js';
3
-
4
- function sprintf(str, ...args) {
5
- return str.replace(/%s/g, () => args.shift());
6
- }
7
-
8
- const keys = {
9
- r: '%s:token:view:%s',
10
- a: '%s:token:add:%s',
11
- w: '%s:token:edit:%s',
12
- e: '%s:token:exec:%s',
13
- };
14
-
15
- async function getToken({
16
- uid, token, mode = 'r', json,
17
- }) {
18
- if (mode === 'r') return token;
19
-
20
- const rclient = getRedis({ db: 0 });
21
-
22
- const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
- const id = await rclient.hget(key, token);
24
- return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
- }
26
-
27
- export default getToken;
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+ import config from '../../config.js';
3
+
4
+ function sprintf(str, ...args) {
5
+ return str.replace(/%s/g, () => args.shift());
6
+ }
7
+
8
+ const keys = {
9
+ r: '%s:token:view:%s',
10
+ a: '%s:token:add:%s',
11
+ w: '%s:token:edit:%s',
12
+ e: '%s:token:exec:%s',
13
+ };
14
+
15
+ async function getToken({
16
+ uid, token, mode = 'r', json,
17
+ }) {
18
+ if (mode === 'r') return token;
19
+
20
+ const rclient = getRedis({ db: 0 });
21
+
22
+ const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
+ const id = await rclient.hget(key, token);
24
+ return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
+ }
26
+
27
+ export default getToken;
@@ -1,13 +1,13 @@
1
- import { access } from 'fs/promises';
2
-
3
- const isFileExists = async (filepath) => {
4
- try {
5
- await access(filepath);
6
- return true;
7
- }
8
- catch (err) {
9
- return false;
10
- }
11
- };
12
-
13
- export default isFileExists;
1
+ import { access } from 'fs/promises';
2
+
3
+ const isFileExists = async (filepath) => {
4
+ try {
5
+ await access(filepath);
6
+ return true;
7
+ }
8
+ catch (err) {
9
+ return false;
10
+ }
11
+ };
12
+
13
+ export default isFileExists;
@@ -1,53 +1,53 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- import config from '../../config.js';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
-
6
- const generateCodes = (ids, userToken) => {
7
- const token = userToken || randomUUID();
8
- const notNullIds = ids.filter((el) => el);
9
- const obj = {};
10
- const codes = notNullIds.reduce((acc, id) => {
11
- const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
- acc[newToken] = id; obj[id] = newToken;
13
- return acc;
14
- }, {});
15
- return { codes, obj };
16
- };
17
-
18
- function setToken({
19
- ids: idsOrigin, mode = 'r', uid, referer, array,
20
- }) {
21
- const rclient2 = getRedis({ db: 0 });
22
- // const rclient5 = getRedis({ db: 0, funcs });
23
-
24
- if (!uid) return { user: 'empty' };
25
- if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
-
27
- const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
- // update/delete
29
-
30
- if (mode === 'r') return null;
31
-
32
- // TODO generate salt
33
- const { codes, obj } = generateCodes(ids, uid);
34
-
35
- if (!Object.keys(codes).length) return { ids: 'empty' };
36
-
37
- rclient2.hmset(`${config.pg.database}:token:${{
38
- e: 'exec', r: 'view', w: 'edit', a: 'add',
39
- }[mode]}:${uid}`, codes);
40
-
41
- // log token for debug. add extra data - uid, mode, date
42
- /* const dt = new Date().toISOString();
43
- const codesLog = Object.keys(codes).reduce((acc, key) => {
44
- acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
- return acc;
46
- }, {});
47
- rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
-
49
- // TODO дополнительно писать в hset token -> uid
50
- return array ? Object.values(obj) : obj;
51
- }
52
-
53
- export default setToken;
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import config from '../../config.js';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+
6
+ const generateCodes = (ids, userToken) => {
7
+ const token = userToken || randomUUID();
8
+ const notNullIds = ids.filter((el) => el);
9
+ const obj = {};
10
+ const codes = notNullIds.reduce((acc, id) => {
11
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
+ acc[newToken] = id; obj[id] = newToken;
13
+ return acc;
14
+ }, {});
15
+ return { codes, obj };
16
+ };
17
+
18
+ function setToken({
19
+ ids: idsOrigin, mode = 'r', uid, referer, array,
20
+ }) {
21
+ const rclient2 = getRedis({ db: 0 });
22
+ // const rclient5 = getRedis({ db: 0, funcs });
23
+
24
+ if (!uid) return { user: 'empty' };
25
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
+
27
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
+ // update/delete
29
+
30
+ if (mode === 'r') return null;
31
+
32
+ // TODO generate salt
33
+ const { codes, obj } = generateCodes(ids, uid);
34
+
35
+ if (!Object.keys(codes).length) return { ids: 'empty' };
36
+
37
+ rclient2.hmset(`${config.pg.database}:token:${{
38
+ e: 'exec', r: 'view', w: 'edit', a: 'add',
39
+ }[mode]}:${uid}`, codes);
40
+
41
+ // log token for debug. add extra data - uid, mode, date
42
+ /* const dt = new Date().toISOString();
43
+ const codesLog = Object.keys(codes).reduce((acc, key) => {
44
+ acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
+ return acc;
46
+ }, {});
47
+ rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
+
49
+ // TODO дополнительно писать в hset token -> uid
50
+ return array ? Object.values(obj) : obj;
51
+ }
52
+
53
+ export default setToken;
package/crud/index.js CHANGED
@@ -1,36 +1,36 @@
1
- import getOpt from './funcs/getOpt.js';
2
- import setOpt from './funcs/setOpt.js';
3
- import isFileExists from './funcs/isFileExists.js';
4
- import dataUpdate from './funcs/dataUpdate.js';
5
- import dataInsert from './funcs/dataInsert.js';
6
-
7
- import update from './controllers/update.js';
8
- import insert from './controllers/insert.js';
9
- import deleteCrud from './controllers/deleteCrud.js';
10
- import getAccessFunc from './funcs/getAccess.js';
11
-
12
- const tableSchema = {
13
- params: {
14
- id: { type: 'string', pattern: '^([\\d\\w]+)$' },
15
- table: { type: 'string', pattern: '^([\\w\\d_.]+)$' },
16
- },
17
- };
18
-
19
- async function plugin(fastify, config = {}) {
20
- const prefix = config.prefix || '/api';
21
- // funcs
22
- fastify.decorate('setOpt', setOpt);
23
- fastify.decorate('getOpt', getOpt);
24
- fastify.decorate('dataUpdate', dataUpdate);
25
- fastify.decorate('dataInsert', dataInsert);
26
- fastify.decorate('getAccess', getAccessFunc);
27
-
28
- fastify.decorate('isFileExists', isFileExists);
29
-
30
- // api
31
- fastify.put(`${prefix}/table/:table/:id`, { schema: tableSchema }, update);
32
- fastify.delete(`${prefix}/table/:table/:id`, { schema: tableSchema }, deleteCrud);
33
- fastify.post(`${prefix}/table/:table`, { schema: tableSchema }, insert);
34
- }
35
-
36
- export default plugin;
1
+ import getOpt from './funcs/getOpt.js';
2
+ import setOpt from './funcs/setOpt.js';
3
+ import isFileExists from './funcs/isFileExists.js';
4
+ import dataUpdate from './funcs/dataUpdate.js';
5
+ import dataInsert from './funcs/dataInsert.js';
6
+
7
+ import update from './controllers/update.js';
8
+ import insert from './controllers/insert.js';
9
+ import deleteCrud from './controllers/deleteCrud.js';
10
+ import getAccessFunc from './funcs/getAccess.js';
11
+
12
+ const tableSchema = {
13
+ params: {
14
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
15
+ table: { type: 'string', pattern: '^([\\w\\d_.]+)$' },
16
+ },
17
+ };
18
+
19
+ async function plugin(fastify, config = {}) {
20
+ const prefix = config.prefix || '/api';
21
+ // funcs
22
+ fastify.decorate('setOpt', setOpt);
23
+ fastify.decorate('getOpt', getOpt);
24
+ fastify.decorate('dataUpdate', dataUpdate);
25
+ fastify.decorate('dataInsert', dataInsert);
26
+ fastify.decorate('getAccess', getAccessFunc);
27
+
28
+ fastify.decorate('isFileExists', isFileExists);
29
+
30
+ // api
31
+ fastify.put(`${prefix}/table/:table/:id`, { schema: tableSchema }, update);
32
+ fastify.delete(`${prefix}/table/:table/:id`, { schema: tableSchema }, deleteCrud);
33
+ fastify.post(`${prefix}/table/:table`, { schema: tableSchema }, insert);
34
+ }
35
+
36
+ export default plugin;
package/index.js CHANGED
@@ -42,7 +42,7 @@ async function plugin(fastify, opt) {
42
42
  fastify.register(import('@opengis/fastify-hb'));
43
43
  fastify.decorate('getFolder', (req, type = 'server') => {
44
44
  if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
45
- const types = { local: req.root, server: req.mapServerRoot };
45
+ const types = { local: req.root || config.root, server: req.mapServerRoot || config.mapServerRoot };
46
46
  const filepath = path.posix.join(types[type] || '/data/local', req.folder || config.folder || '');
47
47
  return filepath;
48
48
  });
@@ -1,76 +1,76 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- const time = Date.now();
5
-
6
- import getPG from '../pg/funcs/getPG.js';
7
-
8
- export default async function execMigrations(opt) {
9
- try {
10
- const pg = opt?.pg || getPG({ name: 'client' });
11
- const rootDir = getCallerDir();
12
- const dir = path.join(rootDir.replace(/\\/g, '/').replace(/^file:\/\/\//, ''), rootDir.endsWith('plugins') ? '../..' : '', 'server/migrations');
13
-
14
- console.log('migrations start', dir, Date.now() - time);
15
- const exists = fs.existsSync(dir);
16
- if (exists) {
17
- // get directory sql file list
18
- const content = fs.readdirSync(dir, { withFileTypes: true })
19
- ?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
20
- ?.map((el) => el.name) || [];
21
-
22
- // execute sql files
23
- if (content?.length) {
24
- await sequence(content, { pg, dir }, execSql);
25
- }
26
- }
27
- console.log('migrations finish', dir, exists, Date.now() - time);
28
- } catch(err) {
29
- console.error('migrations error', err.toString(), Date.now() - time);
30
- }
31
- }
32
-
33
- function getCallerDir() {
34
- const originalFunc = Error.prepareStackTrace;
35
-
36
- let callerfile;
37
- try {
38
- const err = new Error();
39
- let currentfile;
40
-
41
- Error.prepareStackTrace = function (err, stack) { return stack; };
42
-
43
- currentfile = err.stack.shift().getFileName();
44
-
45
- while (err.stack.length) {
46
- callerfile = err.stack.shift().getFileName();
47
-
48
- if(currentfile !== callerfile) break;
49
- }
50
- } catch (err) { }
51
-
52
- Error.prepareStackTrace = originalFunc;
53
-
54
- return path.dirname(callerfile);
55
- }
56
-
57
- function sequence(files, data, fn) {
58
- return files.reduce((promise, filename) => promise.then(() => fn({
59
- ...data, filename,
60
- })), Promise.resolve());
61
- }
62
-
63
- async function execSql({
64
- pg, dir, filename,
65
- }) {
66
- const start = Date.now();
67
- const filepath = path.join(dir, filename);
68
- const sql = fs.readFileSync(filepath, 'utf-8');
69
- try {
70
- console.log(filename, 'start', Date.now() - start);
71
- await pg.query(sql);
72
- console.log(filename, 'finish', Date.now() - start);
73
- } catch (err) {
74
- console.log(filepath, 'error', err.toString(), Date.now() - start);
75
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const time = Date.now();
5
+
6
+ import getPG from '../pg/funcs/getPG.js';
7
+
8
+ export default async function execMigrations(opt) {
9
+ try {
10
+ const pg = opt?.pg || getPG({ name: 'client' });
11
+ const rootDir = getCallerDir();
12
+ const dir = path.join(rootDir.replace(/\\/g, '/').replace(/^file:\/\/\//, ''), rootDir.endsWith('plugins') ? '../..' : '', 'server/migrations');
13
+
14
+ console.log('migrations start', dir, Date.now() - time);
15
+ const exists = fs.existsSync(dir);
16
+ if (exists) {
17
+ // get directory sql file list
18
+ const content = fs.readdirSync(dir, { withFileTypes: true })
19
+ ?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
20
+ ?.map((el) => el.name) || [];
21
+
22
+ // execute sql files
23
+ if (content?.length) {
24
+ await sequence(content, { pg, dir }, execSql);
25
+ }
26
+ }
27
+ console.log('migrations finish', dir, exists, Date.now() - time);
28
+ } catch(err) {
29
+ console.error('migrations error', err.toString(), Date.now() - time);
30
+ }
31
+ }
32
+
33
+ function getCallerDir() {
34
+ const originalFunc = Error.prepareStackTrace;
35
+
36
+ let callerfile;
37
+ try {
38
+ const err = new Error();
39
+ let currentfile;
40
+
41
+ Error.prepareStackTrace = function (err, stack) { return stack; };
42
+
43
+ currentfile = err.stack.shift().getFileName();
44
+
45
+ while (err.stack.length) {
46
+ callerfile = err.stack.shift().getFileName();
47
+
48
+ if(currentfile !== callerfile) break;
49
+ }
50
+ } catch (err) { }
51
+
52
+ Error.prepareStackTrace = originalFunc;
53
+
54
+ return path.dirname(callerfile);
55
+ }
56
+
57
+ function sequence(files, data, fn) {
58
+ return files.reduce((promise, filename) => promise.then(() => fn({
59
+ ...data, filename,
60
+ })), Promise.resolve());
61
+ }
62
+
63
+ async function execSql({
64
+ pg, dir, filename,
65
+ }) {
66
+ const start = Date.now();
67
+ const filepath = path.join(dir, filename);
68
+ const sql = fs.readFileSync(filepath, 'utf-8');
69
+ try {
70
+ console.log(filename, 'start', Date.now() - start);
71
+ await pg.query(sql);
72
+ console.log(filename, 'finish', Date.now() - start);
73
+ } catch (err) {
74
+ console.log(filepath, 'error', err.toString(), Date.now() - start);
75
+ }
76
76
  }
@@ -1,49 +1,49 @@
1
- import path from 'path';
2
- import { existsSync } from 'fs';
3
- import { fileURLToPath } from 'url';
4
-
5
- const fileName = fileURLToPath(import.meta.url);
6
- const dirName = path.dirname(fileName);
7
-
8
- import notification from '../funcs/sendNotification.js';
9
-
10
- export default async function testNotification({
11
- pg, funcs = {}, log, query = {}, session = {},
12
- }) {
13
- const { local } = funcs.config || {};
14
- if (!session?.passport?.user?.user_type?.includes('admin') && !local) {
15
- return { message: 'Forbidden', status: 403 };
16
- }
17
-
18
- const date = new Date().toISOString().split('T')[0];
19
- if (!query.to) {
20
- return { message: 'param to is required', status: 400 };
21
- }
22
-
23
- try {
24
- const {
25
- to, template, table, id, nocache,
26
- } = query;
27
- const file = [path.join(dirName, '../../', 'changelog.md'), path.join(dirName, 'utils', 'pin-m-ty-media-record-outline+303070.png')].filter((el) => existsSync(el));
28
- const data = await notification({
29
- pg,
30
- funcs,
31
- log,
32
- to,
33
- template,
34
- title: `Test Softpro ${date}`,
35
- table,
36
- nocache,
37
- file,
38
- id,
39
- message: `Test mail Softpro ${date} Lorem Ipsum Lorem Ipsum`,
40
- });
41
-
42
- return {
43
- message: data || 'ok',
44
- };
45
- }
46
- catch (err) {
47
- return { error: err.toString(), status: 500 };
48
- }
49
- }
1
+ import path from 'path';
2
+ import { existsSync } from 'fs';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const fileName = fileURLToPath(import.meta.url);
6
+ const dirName = path.dirname(fileName);
7
+
8
+ import notification from '../funcs/sendNotification.js';
9
+
10
+ export default async function testNotification({
11
+ pg, funcs = {}, log, query = {}, session = {},
12
+ }) {
13
+ const { local } = funcs.config || {};
14
+ if (!session?.passport?.user?.user_type?.includes('admin') && !local) {
15
+ return { message: 'Forbidden', status: 403 };
16
+ }
17
+
18
+ const date = new Date().toISOString().split('T')[0];
19
+ if (!query.to) {
20
+ return { message: 'param to is required', status: 400 };
21
+ }
22
+
23
+ try {
24
+ const {
25
+ to, template, table, id, nocache,
26
+ } = query;
27
+ const file = [path.join(dirName, '../../', 'changelog.md'), path.join(dirName, 'utils', 'pin-m-ty-media-record-outline+303070.png')].filter((el) => existsSync(el));
28
+ const data = await notification({
29
+ pg,
30
+ funcs,
31
+ log,
32
+ to,
33
+ template,
34
+ title: `Test Softpro ${date}`,
35
+ table,
36
+ nocache,
37
+ file,
38
+ id,
39
+ message: `Test mail Softpro ${date} Lorem Ipsum Lorem Ipsum`,
40
+ });
41
+
42
+ return {
43
+ message: data || 'ok',
44
+ };
45
+ }
46
+ catch (err) {
47
+ return { error: err.toString(), status: 500 };
48
+ }
49
+ }