@opengis/fastify-table 1.0.74 → 1.0.76

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 (64) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +237 -229
  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/deleteCrud.js +1 -1
  10. package/crud/controllers/utils/checkXSS.js +45 -45
  11. package/crud/controllers/utils/xssInjection.js +72 -72
  12. package/crud/funcs/dataDelete.js +15 -15
  13. package/crud/funcs/dataUpdate.js +24 -24
  14. package/crud/funcs/getAccess.js +2 -1
  15. package/crud/funcs/getToken.js +27 -27
  16. package/crud/funcs/isFileExists.js +13 -13
  17. package/crud/funcs/setToken.js +53 -53
  18. package/crud/index.js +36 -36
  19. package/index.js +97 -97
  20. package/migration/exec.migrations.js +75 -75
  21. package/notification/controllers/testEmail.js +49 -49
  22. package/notification/funcs/sendNotification.js +111 -111
  23. package/notification/funcs/utils/sendEmail.js +39 -39
  24. package/notification/index.js +38 -38
  25. package/package.json +26 -26
  26. package/pg/funcs/getPG.js +30 -30
  27. package/redis/funcs/getRedis.js +23 -23
  28. package/server/migrations/0.sql +64 -13
  29. package/server/migrations/crm.sql +150 -150
  30. package/server/migrations/log.sql +43 -43
  31. package/server.js +14 -14
  32. package/table/controllers/card.js +44 -44
  33. package/table/controllers/filter.js +37 -37
  34. package/table/controllers/form.js +28 -28
  35. package/table/controllers/search.js +72 -72
  36. package/table/controllers/suggest.js +62 -62
  37. package/table/controllers/table.js +44 -44
  38. package/table/controllers/utils/getSelectMeta.js +66 -66
  39. package/table/controllers/utils/getTemplate.js +28 -28
  40. package/table/controllers/utils/getTemplates.js +18 -18
  41. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  42. package/table/funcs/metaFormat/index.js +27 -27
  43. package/table/index.js +78 -78
  44. package/test/api/crud.test.js +18 -11
  45. package/test/api/crud.xss.test.js +72 -72
  46. package/test/api/notification.test.js +37 -37
  47. package/test/api/table.test.js +57 -57
  48. package/test/api/widget.test.js +114 -114
  49. package/test/config.example +18 -18
  50. package/test/funcs/crud.test.js +76 -76
  51. package/test/funcs/notification.test.js +31 -31
  52. package/test/funcs/pg.test.js +34 -34
  53. package/test/funcs/redis.test.js +19 -19
  54. package/test/templates/cls/test.json +9 -9
  55. package/test/templates/form/cp_building.form.json +32 -32
  56. package/test/templates/select/account_id.json +3 -3
  57. package/test/templates/select/storage.data.json +2 -2
  58. package/test/templates/table/gis.dataset.table.json +20 -20
  59. package/util/controllers/next.id.js +4 -4
  60. package/util/controllers/properties.add.js +50 -50
  61. package/util/controllers/properties.get.js +19 -19
  62. package/util/controllers/status.monitor.js +3 -0
  63. package/util/index.js +4 -3
  64. 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
@@ -1,97 +1,97 @@
1
- import path from 'path';
2
- import { existsSync, readdirSync, readFileSync } from 'fs';
3
-
4
- import fp from 'fastify-plugin';
5
- import config from './config.js';
6
- // import rclient from './redis/client.js';
7
-
8
- import redisPlugin from './redis/index.js';
9
- import pgPlugin from './pg/index.js';
10
- import tablePlugin from './table/index.js';
11
- import notificationPlugin from './notification/index.js';
12
- import widgetPlugin from './widget/index.js';
13
- import crudPlugin from './crud/index.js';
14
- import policyPlugin from './policy/index.js';
15
- import utilPlugin from './util/index.js';
16
- import cronPlugin from './cron/index.js';
17
-
18
- import pgClients from './pg/pgClients.js';
19
-
20
- import execMigrations from './migration/exec.migrations.js';
21
-
22
- async function plugin(fastify, opt) {
23
- // console.log(opt);
24
- config.pg = opt.pg;
25
- config.redis = opt.redis;
26
- config.root = opt.root;
27
- config.mapServerRoot = opt.mapServerRoot;
28
-
29
- // independent npm start / unit test
30
- if (!fastify.config) {
31
- fastify.decorate('config', config);
32
- }
33
-
34
- fastify.register(import('@fastify/sensible'), {
35
- errorHandler: false,
36
- });
37
-
38
- fastify.register(import('@fastify/url-data'), {
39
- errorHandler: false,
40
- });
41
-
42
- fastify.register(import('@opengis/fastify-hb'));
43
- fastify.decorate('getFolder', (req, type = 'server') => {
44
- if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
45
- const types = { local: req.root, server: req.mapServerRoot };
46
- const filepath = path.posix.join(types[type] || '/data/local', req.folder || config.folder || '');
47
- return filepath;
48
- });
49
-
50
- fastify.addHook('onListen', async () => {
51
- const { client } = pgClients;
52
- if (client?.pk?.['crm.cls']) {
53
- const clsDir = path.join(process.cwd(), 'server/templates/cls');
54
- const files = existsSync(clsDir) ? readdirSync(clsDir) : [];
55
- if (files.length) {
56
- const res = await Promise.all(files.map(async (filename) => {
57
- const filepath = path.join(clsDir, filename);
58
- const data = JSON.parse(readFileSync(filepath));
59
- return { name: path.parse(filename).name, data };
60
- }));
61
- await client.query('truncate table crm.cls');
62
- const { rows } = await client.query(`insert into crm.cls(name, type)
63
- select value->>'name', 'json' from json_array_elements($1) returning cls_id as id, name`, [JSON.stringify(res).replace(/'/g, "''")]);
64
- rows.forEach((row) => Object.assign(row, { data: res.find((cls) => row.name === cls.name)?.data }));
65
- const sql = `insert into crm.cls(code, name, parent)
66
- select json_array_elements(value->'data')->>'id', json_array_elements(value->'data')->>'text', value->>'name' from json_array_elements($1)`;
67
- await client.query(sql, [JSON.stringify(rows).replace(/'/g, "''")]);
68
- }
69
- }
70
- // call from another repo / project
71
- fastify.execMigrations = execMigrations;
72
- // execute core migrations
73
- await fastify.execMigrations();
74
- });
75
- if (!fastify.funcs) {
76
- fastify.addHook('onRequest', async (req) => {
77
- req.funcs = fastify;
78
- if (!req.user && req.session?.passport?.user) {
79
- const { user } = req.session?.passport || {};
80
- req.user = user;
81
- }
82
- });
83
- // fastify.decorateRequest('funcs', fastify);
84
- }
85
-
86
- policyPlugin(fastify);
87
- redisPlugin(fastify);
88
- await pgPlugin(fastify, opt);
89
- tablePlugin(fastify, opt);
90
- crudPlugin(fastify, opt);
91
- notificationPlugin(fastify, opt);
92
- widgetPlugin(fastify, opt);
93
- utilPlugin(fastify, opt);
94
- cronPlugin(fastify, opt);
95
- }
96
- export default fp(plugin);
97
- // export { rclient };
1
+ import path from 'path';
2
+ import { existsSync, readdirSync, readFileSync } from 'fs';
3
+
4
+ import fp from 'fastify-plugin';
5
+ import config from './config.js';
6
+ // import rclient from './redis/client.js';
7
+
8
+ import redisPlugin from './redis/index.js';
9
+ import pgPlugin from './pg/index.js';
10
+ import tablePlugin from './table/index.js';
11
+ import notificationPlugin from './notification/index.js';
12
+ import widgetPlugin from './widget/index.js';
13
+ import crudPlugin from './crud/index.js';
14
+ import policyPlugin from './policy/index.js';
15
+ import utilPlugin from './util/index.js';
16
+ import cronPlugin from './cron/index.js';
17
+
18
+ import pgClients from './pg/pgClients.js';
19
+
20
+ import execMigrations from './migration/exec.migrations.js';
21
+
22
+ async function plugin(fastify, opt) {
23
+ // console.log(opt);
24
+ config.pg = opt.pg;
25
+ config.redis = opt.redis;
26
+ config.root = opt.root;
27
+ config.mapServerRoot = opt.mapServerRoot;
28
+
29
+ // independent npm start / unit test
30
+ if (!fastify.config) {
31
+ fastify.decorate('config', config);
32
+ }
33
+
34
+ fastify.register(import('@fastify/sensible'), {
35
+ errorHandler: false,
36
+ });
37
+
38
+ fastify.register(import('@fastify/url-data'), {
39
+ errorHandler: false,
40
+ });
41
+
42
+ fastify.register(import('@opengis/fastify-hb'));
43
+ fastify.decorate('getFolder', (req, type = 'server') => {
44
+ if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
45
+ const types = { local: req.root, server: req.mapServerRoot };
46
+ const filepath = path.posix.join(types[type] || '/data/local', req.folder || config.folder || '');
47
+ return filepath;
48
+ });
49
+
50
+ fastify.addHook('onListen', async () => {
51
+ const { client } = pgClients;
52
+ if (client?.pk?.['crm.cls']) {
53
+ const clsDir = path.join(process.cwd(), 'server/templates/cls');
54
+ const files = existsSync(clsDir) ? readdirSync(clsDir) : [];
55
+ if (files.length) {
56
+ const res = await Promise.all(files.map(async (filename) => {
57
+ const filepath = path.join(clsDir, filename);
58
+ const data = JSON.parse(readFileSync(filepath));
59
+ return { name: path.parse(filename).name, data };
60
+ }));
61
+ await client.query('truncate table crm.cls');
62
+ const { rows } = await client.query(`insert into crm.cls(name, type)
63
+ select value->>'name', 'json' from json_array_elements($1) returning cls_id as id, name`, [JSON.stringify(res).replace(/'/g, "''")]);
64
+ rows.forEach((row) => Object.assign(row, { data: res.find((cls) => row.name === cls.name)?.data }));
65
+ const sql = `insert into crm.cls(code, name, parent)
66
+ select json_array_elements(value->'data')->>'id', json_array_elements(value->'data')->>'text', value->>'name' from json_array_elements($1)`;
67
+ await client.query(sql, [JSON.stringify(rows).replace(/'/g, "''")]);
68
+ }
69
+ }
70
+ // call from another repo / project
71
+ fastify.execMigrations = execMigrations;
72
+ // execute core migrations
73
+ await fastify.execMigrations();
74
+ });
75
+ if (!fastify.funcs) {
76
+ fastify.addHook('onRequest', async (req) => {
77
+ req.funcs = fastify;
78
+ if (!req.user && req.session?.passport?.user) {
79
+ const { user } = req.session?.passport || {};
80
+ req.user = user;
81
+ }
82
+ });
83
+ // fastify.decorateRequest('funcs', fastify);
84
+ }
85
+
86
+ policyPlugin(fastify);
87
+ redisPlugin(fastify);
88
+ await pgPlugin(fastify, opt);
89
+ tablePlugin(fastify, opt);
90
+ crudPlugin(fastify, opt);
91
+ notificationPlugin(fastify, opt);
92
+ widgetPlugin(fastify, opt);
93
+ utilPlugin(fastify, opt);
94
+ cronPlugin(fastify, opt);
95
+ }
96
+ export default fp(plugin);
97
+ // export { rclient };
@@ -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
  }