@opengis/fastify-table 1.1.9 → 1.1.11
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.
- package/.eslintrc.cjs +42 -42
- package/Changelog.md +305 -305
- package/crud/controllers/deleteCrud.js +22 -22
- package/crud/controllers/insert.js +61 -61
- package/crud/controllers/update.js +62 -62
- package/crud/funcs/dataDelete.js +19 -19
- package/crud/funcs/dataInsert.js +30 -30
- package/crud/funcs/dataUpdate.js +48 -36
- package/crud/funcs/getAccess.js +53 -53
- package/crud/funcs/getOpt.js +10 -10
- package/crud/funcs/setOpt.js +16 -16
- package/crud/funcs/utils/logChanges.js +76 -76
- package/crud/index.js +36 -36
- package/helper.js +28 -28
- package/index.js +97 -97
- package/migration/exec.migrations.js +79 -79
- package/notification/controllers/userNotifications.js +19 -19
- package/notification/funcs/addNotification.js +8 -8
- package/notification/funcs/sendNotification.js +111 -111
- package/package.json +26 -26
- package/pg/funcs/getMeta.js +27 -27
- package/pg/pgClients.js +20 -20
- package/policy/funcs/checkPolicy.js +83 -83
- package/policy/funcs/sqlInjection.js +33 -33
- package/policy/index.js +14 -14
- package/redis/client.js +8 -8
- package/redis/funcs/redisClients.js +2 -2
- package/redis/index.js +19 -19
- package/server/migrations/0.sql +78 -78
- package/server/migrations/properties.sql +30 -30
- package/server/migrations/roles.sql +164 -164
- package/server/migrations/users.sql +89 -89
- package/table/controllers/data.js +103 -103
- package/table/controllers/filter.js +40 -37
- package/table/controllers/search.js +80 -80
- package/table/controllers/suggest.js +79 -79
- package/table/controllers/table.js +52 -52
- package/table/controllers/utils/addTemplateDir.js +8 -8
- package/table/controllers/utils/getSelect.js +19 -19
- package/table/controllers/utils/getSelectMeta.js +66 -66
- package/table/controllers/utils/getTemplate_old.js +28 -28
- package/table/controllers/utils/getTemplates.js +18 -18
- package/table/controllers/utils/gisIRColumn.js +68 -68
- package/table/controllers/utils/loadTemplate.js +1 -1
- package/table/controllers/utils/loadTemplatePath.js +1 -1
- package/table/controllers/utils/userTemplateDir.js +1 -1
- package/table/funcs/getFilterSQL/index.js +79 -79
- package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
- package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
- package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
- package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
- package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
- package/table/funcs/metaFormat/getSelectVal.js +20 -20
- package/table/funcs/metaFormat/index.js +28 -28
- package/table/index.js +84 -84
- package/test/api/crud.test.js +89 -89
- package/test/api/suggest.test.js +66 -66
- package/test/api/table.test.js +89 -89
- package/test/api/widget.test.js +117 -117
- package/test/templates/select/test.storage.data.json +3 -3
- package/test/templates/select/test.suggest.ato_new.json +3 -3
- package/test/templates/select/test.suggest.ato_new.sql +25 -25
- package/test/templates/select/test.suggest.data.json +4 -4
- package/test/templates/select/test.suggest.parent.sql +1 -1
- package/util/controllers/properties.add.js +57 -57
- package/util/controllers/status.monitor.js +8 -8
- package/utils.js +48 -48
- package/widget/controllers/utils/historyFormat.js +76 -76
- package/widget/controllers/utils/obj2db.js +13 -13
- package/widget/controllers/widget.del.js +44 -44
- package/widget/controllers/widget.get.js +98 -98
- package/widget/controllers/widget.set.js +76 -76
- package/widget/index.js +40 -40
|
@@ -1,76 +1,76 @@
|
|
|
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 (typeof value === 'object' || fieldType.includes('json')) {
|
|
16
|
-
if (Array.isArray(value)) {
|
|
17
|
-
return `'${JSON.stringify(value)}'`;
|
|
18
|
-
}
|
|
19
|
-
return `'${JSON.stringify(value)}'`;
|
|
20
|
-
}
|
|
21
|
-
if (Array.isArray(value)) {
|
|
22
|
-
return `'{ ${value.join(',')} }'::${fieldType}`;
|
|
23
|
-
}
|
|
24
|
-
return `'${value || null}'`;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export default async function logChanges({
|
|
28
|
-
pg, table, id, data, uid = 1, type,
|
|
29
|
-
}) {
|
|
30
|
-
if (!id) {
|
|
31
|
-
console.error('param id is required');
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
if (!table || !pg.pk?.[table]) {
|
|
35
|
-
console.error('table not found');
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
|
|
39
|
-
console.error('log table not found');
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
if (!type) {
|
|
43
|
-
console.error('invalid type');
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
try {
|
|
48
|
-
const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
|
|
49
|
-
values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
|
|
50
|
-
|
|
51
|
-
const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
|
|
52
|
-
const columnList = fields.map((el) => el?.name);
|
|
53
|
-
const q = `select ${Object.keys(data || {}).filter((el) => columnList.includes(el)).join(',') || '*'} from ${table} where ${pg.pk?.[table]}=$1`;
|
|
54
|
-
// console.log(q, type, id);
|
|
55
|
-
|
|
56
|
-
const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
|
|
57
|
-
|
|
58
|
-
const fieldTypes = fields?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: pg.pgType[curr.dataTypeID] }), {}) || {};
|
|
59
|
-
const q1 = Object.keys(data || {}).map((el) => `insert into log.table_changes_data(change_id,entity_key,value_old,value_new)
|
|
60
|
-
values('${changeId}', '${el}', ${formatData(fieldTypes[el], old[el])}, ${formatData(fieldTypes[el], data[el])}) returning *`).join(';\n');
|
|
61
|
-
// console.log(q1);
|
|
62
|
-
const res = await pg.query(q1);
|
|
63
|
-
|
|
64
|
-
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 }), {});
|
|
65
|
-
// console.log('logChanges OK', type);
|
|
66
|
-
return {
|
|
67
|
-
change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
catch (err) {
|
|
71
|
-
console.error('logChanges error', type, table, id, data, err.toString());
|
|
72
|
-
return {
|
|
73
|
-
error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
}
|
|
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 (typeof value === 'object' || fieldType.includes('json')) {
|
|
16
|
+
if (Array.isArray(value)) {
|
|
17
|
+
return `'${JSON.stringify(value)}'`;
|
|
18
|
+
}
|
|
19
|
+
return `'${JSON.stringify(value)}'`;
|
|
20
|
+
}
|
|
21
|
+
if (Array.isArray(value)) {
|
|
22
|
+
return `'{ ${value.join(',')} }'::${fieldType}`;
|
|
23
|
+
}
|
|
24
|
+
return `'${value || null}'`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export default async function logChanges({
|
|
28
|
+
pg, table, id, data, uid = 1, type,
|
|
29
|
+
}) {
|
|
30
|
+
if (!id) {
|
|
31
|
+
console.error('param id is required');
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (!table || !pg.pk?.[table]) {
|
|
35
|
+
console.error('table not found');
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (!pg.pk?.['log.table_changes'] || !pg.pk?.['log.table_changes_data']) {
|
|
39
|
+
console.error('log table not found');
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
if (!type) {
|
|
43
|
+
console.error('invalid type');
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
const { change_id: changeId } = await pg.query(`insert into log.table_changes(change_date,change_type,change_user_id,entity_type,entity_id)
|
|
49
|
+
values(CURRENT_DATE, $1, $2, $3, $4) returning change_id`, [type, uid, table, id]).then((res) => res.rows?.[0] || {});
|
|
50
|
+
|
|
51
|
+
const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
|
|
52
|
+
const columnList = fields.map((el) => el?.name);
|
|
53
|
+
const q = `select ${Object.keys(data || {}).filter((el) => columnList.includes(el)).join(',') || '*'} from ${table} where ${pg.pk?.[table]}=$1`;
|
|
54
|
+
// console.log(q, type, id);
|
|
55
|
+
|
|
56
|
+
const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
|
|
57
|
+
|
|
58
|
+
const fieldTypes = fields?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: pg.pgType[curr.dataTypeID] }), {}) || {};
|
|
59
|
+
const q1 = Object.keys(data || {}).map((el) => `insert into log.table_changes_data(change_id,entity_key,value_old,value_new)
|
|
60
|
+
values('${changeId}', '${el}', ${formatData(fieldTypes[el], old[el])}, ${formatData(fieldTypes[el], data[el])}) returning *`).join(';\n');
|
|
61
|
+
// console.log(q1);
|
|
62
|
+
const res = await pg.query(q1);
|
|
63
|
+
|
|
64
|
+
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 }), {});
|
|
65
|
+
// console.log('logChanges OK', type);
|
|
66
|
+
return {
|
|
67
|
+
change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
console.error('logChanges error', type, table, id, data, err.toString());
|
|
72
|
+
return {
|
|
73
|
+
error: err.toString(), entity_type: table, entity_id: id, uid, change_type: type,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
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/helper.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
// This file contains code that we reuse
|
|
2
|
-
// between our tests.
|
|
3
|
-
import Fastify from 'fastify';
|
|
4
|
-
import config from './test/config.js';
|
|
5
|
-
import appService from './index.js';
|
|
6
|
-
|
|
7
|
-
import rclient from './redis/client.js';
|
|
8
|
-
import pgClients from './pg/pgClients.js';
|
|
9
|
-
|
|
10
|
-
// automatically build and tear down our instance
|
|
11
|
-
async function build(t) {
|
|
12
|
-
// you can set all the options supported by the fastify CLI command
|
|
13
|
-
// const argv = [AppPath]
|
|
14
|
-
process.env.NODE_ENV = 'production';
|
|
15
|
-
const app = Fastify({ logger: false });
|
|
16
|
-
app.register(appService, config);
|
|
17
|
-
// close the app after we are done
|
|
18
|
-
t.after(() => {
|
|
19
|
-
// console.log('close app');
|
|
20
|
-
pgClients.client.end();
|
|
21
|
-
rclient.quit();
|
|
22
|
-
app.close();
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
return app;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export default build;
|
|
1
|
+
// This file contains code that we reuse
|
|
2
|
+
// between our tests.
|
|
3
|
+
import Fastify from 'fastify';
|
|
4
|
+
import config from './test/config.js';
|
|
5
|
+
import appService from './index.js';
|
|
6
|
+
|
|
7
|
+
import rclient from './redis/client.js';
|
|
8
|
+
import pgClients from './pg/pgClients.js';
|
|
9
|
+
|
|
10
|
+
// automatically build and tear down our instance
|
|
11
|
+
async function build(t) {
|
|
12
|
+
// you can set all the options supported by the fastify CLI command
|
|
13
|
+
// const argv = [AppPath]
|
|
14
|
+
process.env.NODE_ENV = 'production';
|
|
15
|
+
const app = Fastify({ logger: false });
|
|
16
|
+
app.register(appService, config);
|
|
17
|
+
// close the app after we are done
|
|
18
|
+
t.after(() => {
|
|
19
|
+
// console.log('close app');
|
|
20
|
+
pgClients.client.end();
|
|
21
|
+
rclient.quit();
|
|
22
|
+
app.close();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
return app;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default build;
|
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 || config.root, server: req.mapServerRoot || config.mapServerRoot };
|
|
46
|
-
const filepath = path.posix.join(types[type] || `/data/local/${req.pg?.options?.database || ''}`, 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 || config.root, server: req.mapServerRoot || config.mapServerRoot };
|
|
46
|
+
const filepath = path.posix.join(types[type] || `/data/local/${req.pg?.options?.database || ''}`, 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,79 +1,79 @@
|
|
|
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
|
-
function getCallerDir() {
|
|
9
|
-
const originalFunc = Error.prepareStackTrace;
|
|
10
|
-
|
|
11
|
-
let callerfile;
|
|
12
|
-
try {
|
|
13
|
-
const err = new Error();
|
|
14
|
-
// let currentfile;
|
|
15
|
-
|
|
16
|
-
Error.prepareStackTrace = function (err, stack) { return stack; };
|
|
17
|
-
|
|
18
|
-
const currentfile = err.stack.shift().getFileName();
|
|
19
|
-
|
|
20
|
-
while (err.stack.length) {
|
|
21
|
-
callerfile = err.stack.shift().getFileName();
|
|
22
|
-
|
|
23
|
-
if (currentfile !== callerfile) break;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
catch (err) { }
|
|
27
|
-
|
|
28
|
-
Error.prepareStackTrace = originalFunc;
|
|
29
|
-
|
|
30
|
-
return path.dirname(callerfile);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function sequence(files, data, fn) {
|
|
34
|
-
return files.reduce((promise, filename) => promise.then(() => fn({
|
|
35
|
-
...data, filename,
|
|
36
|
-
})), Promise.resolve());
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function execSql({
|
|
40
|
-
pg, dir, filename,
|
|
41
|
-
}) {
|
|
42
|
-
const start = Date.now();
|
|
43
|
-
const filepath = path.join(dir, filename);
|
|
44
|
-
const sql = fs.readFileSync(filepath, 'utf-8');
|
|
45
|
-
try {
|
|
46
|
-
console.log(filename, 'start', Date.now() - start);
|
|
47
|
-
await pg.query(sql);
|
|
48
|
-
console.log(filename, 'finish', Date.now() - start);
|
|
49
|
-
}
|
|
50
|
-
catch (err) {
|
|
51
|
-
console.log(filepath, 'error', err.toString(), Date.now() - start);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export default async function execMigrations(opt) {
|
|
56
|
-
try {
|
|
57
|
-
const pg = opt?.pg || getPG({ name: 'client' });
|
|
58
|
-
const rootDir = getCallerDir();
|
|
59
|
-
const dir = path.join(rootDir.replace(/\\/g, '/').replace(/^file:\/\/\//, ''), rootDir.endsWith('plugins') ? '../..' : '', 'server/migrations');
|
|
60
|
-
|
|
61
|
-
console.log('migrations start', dir, Date.now() - time);
|
|
62
|
-
const exists = fs.existsSync(dir);
|
|
63
|
-
if (exists) {
|
|
64
|
-
// get directory sql file list
|
|
65
|
-
const content = fs.readdirSync(dir, { withFileTypes: true })
|
|
66
|
-
?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
|
|
67
|
-
?.map((el) => el.name) || [];
|
|
68
|
-
|
|
69
|
-
// execute sql files
|
|
70
|
-
if (content?.length) {
|
|
71
|
-
await sequence(content, { pg, dir }, execSql);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
console.log('migrations finish', dir, exists, Date.now() - time);
|
|
75
|
-
}
|
|
76
|
-
catch (err) {
|
|
77
|
-
console.error('migrations error', err.toString(), Date.now() - time);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
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
|
+
function getCallerDir() {
|
|
9
|
+
const originalFunc = Error.prepareStackTrace;
|
|
10
|
+
|
|
11
|
+
let callerfile;
|
|
12
|
+
try {
|
|
13
|
+
const err = new Error();
|
|
14
|
+
// let currentfile;
|
|
15
|
+
|
|
16
|
+
Error.prepareStackTrace = function (err, stack) { return stack; };
|
|
17
|
+
|
|
18
|
+
const currentfile = err.stack.shift().getFileName();
|
|
19
|
+
|
|
20
|
+
while (err.stack.length) {
|
|
21
|
+
callerfile = err.stack.shift().getFileName();
|
|
22
|
+
|
|
23
|
+
if (currentfile !== callerfile) break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch (err) { }
|
|
27
|
+
|
|
28
|
+
Error.prepareStackTrace = originalFunc;
|
|
29
|
+
|
|
30
|
+
return path.dirname(callerfile);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function sequence(files, data, fn) {
|
|
34
|
+
return files.reduce((promise, filename) => promise.then(() => fn({
|
|
35
|
+
...data, filename,
|
|
36
|
+
})), Promise.resolve());
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function execSql({
|
|
40
|
+
pg, dir, filename,
|
|
41
|
+
}) {
|
|
42
|
+
const start = Date.now();
|
|
43
|
+
const filepath = path.join(dir, filename);
|
|
44
|
+
const sql = fs.readFileSync(filepath, 'utf-8');
|
|
45
|
+
try {
|
|
46
|
+
console.log(filename, 'start', Date.now() - start);
|
|
47
|
+
await pg.query(sql);
|
|
48
|
+
console.log(filename, 'finish', Date.now() - start);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
console.log(filepath, 'error', err.toString(), Date.now() - start);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export default async function execMigrations(opt) {
|
|
56
|
+
try {
|
|
57
|
+
const pg = opt?.pg || getPG({ name: 'client' });
|
|
58
|
+
const rootDir = getCallerDir();
|
|
59
|
+
const dir = path.join(rootDir.replace(/\\/g, '/').replace(/^file:\/\/\//, ''), rootDir.endsWith('plugins') ? '../..' : '', 'server/migrations');
|
|
60
|
+
|
|
61
|
+
console.log('migrations start', dir, Date.now() - time);
|
|
62
|
+
const exists = fs.existsSync(dir);
|
|
63
|
+
if (exists) {
|
|
64
|
+
// get directory sql file list
|
|
65
|
+
const content = fs.readdirSync(dir, { withFileTypes: true })
|
|
66
|
+
?.filter((el) => el.isFile() && path.extname(el.name) === '.sql')
|
|
67
|
+
?.map((el) => el.name) || [];
|
|
68
|
+
|
|
69
|
+
// execute sql files
|
|
70
|
+
if (content?.length) {
|
|
71
|
+
await sequence(content, { pg, dir }, execSql);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
console.log('migrations finish', dir, exists, Date.now() - time);
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
console.error('migrations error', err.toString(), Date.now() - time);
|
|
78
|
+
}
|
|
79
|
+
}
|