@opengis/fastify-table 1.4.23 → 1.4.24

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.4.23",
3
+ "version": "1.4.24",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "keywords": [
@@ -41,8 +41,9 @@ export default async function dataInsert({
41
41
  // for transactions
42
42
  const isClient = typeof pg.query === 'function' && typeof pg.release === 'function';
43
43
  const client = isClient ? pg : await pg.connect();
44
+
44
45
  if (!isClient) {
45
- client.caller = 'dataInsert';
46
+ // client.caller = 'dataInsert';
46
47
  }
47
48
 
48
49
  if (isClient || !client.pk) {
@@ -54,7 +55,7 @@ export default async function dataInsert({
54
55
  }
55
56
 
56
57
  try {
57
- if (client.caller === 'dataInsert') {
58
+ if (!isClient) {
58
59
  await client.query('begin;');
59
60
  }
60
61
  const res = await client.query(insertQuery, args).then(el => el || {});
@@ -107,7 +108,7 @@ export default async function dataInsert({
107
108
  });
108
109
 
109
110
  if (config.redis) { rclient.incr(`pg:${table}:crud`); }
110
- if (client.caller === 'dataInsert') {
111
+ if (!isClient) {
111
112
  await client.query('commit;');
112
113
  }
113
114
  return res;
@@ -116,13 +117,13 @@ export default async function dataInsert({
116
117
  logger.file('crud/insert', {
117
118
  error: err.toString(), stack: err.stack, table, id, referer, uid, form: tokenData?.form,
118
119
  });
119
- if (client.caller === 'dataInsert') {
120
+ if (!isClient) {
120
121
  await client.query('rollback;');
121
122
  }
122
123
  throw err;
123
124
  }
124
125
  finally {
125
- if (client.caller === 'dataInsert') {
126
+ if (!isClient) {
126
127
  client.release();
127
128
  }
128
129
  }
@@ -0,0 +1,23 @@
1
+ /* eslint-disable camelcase */
2
+ const table = 'admin.properties';
3
+
4
+ import { pgClients, getTemplatePath, getTemplate } from '../../../../utils.js';
5
+
6
+ export default async function getSettingsApp({
7
+ pg = pgClients.client,
8
+ }, reply) {
9
+ const time = Date.now();
10
+
11
+ if (!pg.pk?.[table]) {
12
+ return reply.status(404).send('table not found');
13
+ }
14
+
15
+ const { rows = [] } = await pg.query('select property_key as key, property_text, property_json from admin.properties');
16
+
17
+ const settings = rows.reduce((acc, { key, property_text, property_json }) => ({ ...acc, [key]: property_text || property_json }), {});
18
+
19
+ const forms = await Promise.all(getTemplatePath('setting')
20
+ .map(async (el) => ({ name: el[0], body: await getTemplate('setting', el[0]) })));
21
+
22
+ return reply.status(200).send({ time: Date.now() - time, forms, settings });
23
+ }
@@ -0,0 +1,50 @@
1
+ const table = 'admin.properties';
2
+
3
+ import { dataInsert, pgClients } from '../../../../utils.js';
4
+
5
+ function checkValueType(val) {
6
+ if (val) {
7
+ if (typeof val === 'object') {
8
+ return 'property_json';
9
+ }
10
+ if (typeof val === 'number' && (!/\D/.test(val.toString()) && val.toString().length < 10)) {
11
+ return 'property_int';
12
+ }
13
+ }
14
+ return 'property_text';
15
+ }
16
+
17
+ export default async function postSettingsApp({
18
+ pg = pgClients.client, body = {}, user = {}, uid = user?.uid,
19
+ }, reply) {
20
+ if (!user?.user_type?.includes?.('admin')) {
21
+ return reply.status(403).send('access restricted');
22
+ }
23
+ const { key, val } = body;
24
+
25
+ if ((!key || !val) && !Object.keys(body).length) {
26
+ return reply.status(400).send('not enough body params');
27
+ }
28
+
29
+ if (!pg?.pk?.[table]) {
30
+ return reply.status(404).send('table not found');
31
+ }
32
+
33
+ const keys = Object.keys(body);
34
+ await pg.query(`delete from ${table} where property_key=any($1)`, [keys]);
35
+
36
+ await Promise.all(keys.filter(el => body[el]).map(async (el) => {
37
+ const columnType = table === 'admin.user_properties'
38
+ ? 'property_json'
39
+ : checkValueType(body[el]);
40
+
41
+ await dataInsert({
42
+ pg,
43
+ table,
44
+ data: { property_key: el, [columnType]: body[el] },
45
+ uid,
46
+ });
47
+ }));
48
+
49
+ return reply.status(200).send('ok');
50
+ }
@@ -0,0 +1,112 @@
1
+ import { pgClients, getMeta, getTemplate } from '../../../../utils.js';
2
+
3
+ import getColumnMetaData from '../utils/getColumnMetaData.js';
4
+
5
+ /**
6
+ *
7
+ * @method GET
8
+ * @priority 4
9
+ * @alias getSettingsTable
10
+ * @type api
11
+ * @tag custom
12
+
13
+ * @returns {String} message and status
14
+ */
15
+
16
+ export default async function getSettingsTable({
17
+ pg = pgClients.client, params = {}, user = {}, query = {},
18
+ }, reply) {
19
+ const { table, entity } = params;
20
+ const { uid } = user;
21
+ const time = [];
22
+
23
+ if (!uid) {
24
+ return reply.status(401).send('unauthorized');
25
+ }
26
+
27
+ if (!table) {
28
+ return reply.status(400).send('not enough params: table');
29
+ }
30
+
31
+ const loadTable = await getTemplate('table', table);
32
+
33
+ const tableName = loadTable?.table || table;
34
+ const meta = await getMeta({ pg, table: tableName });
35
+ const { view, pk } = meta || {};
36
+ time.push(Date.now());
37
+
38
+ if (!pk && !view) {
39
+ return reply.status(400).send(`table primary key not found: ${tableName}`);
40
+ }
41
+
42
+ const { rows: geometry } = meta?.geom
43
+ ? await pg.queryCache(`select st_geometrytype(${meta?.geom}) as type ,count(*)
44
+ from ${tableName} group by st_geometrytype(${meta?.geom})`, { table: tableName }) : [];
45
+ time.push(Date.now());
46
+
47
+ const stat = !view ? await getColumnMetaData({ pg, table: tableName }) : {};
48
+ time.push(Date.now());
49
+
50
+ const { total = 0 } = await pg.queryCache(`select count(*) as total from ${tableName}`, { table: tableName })
51
+ .then(el => el.rows?.[0] || {});
52
+ time.push(Date.now());
53
+
54
+ const { property_json: customColumns = [] } = await pg.query(`select property_json::json from setting.property
55
+ where property_entity='customColumn' and object_id=$1`, [table]).then(el => el.rows?.[0] || {});
56
+
57
+ const { property_json: tableSettingColumns } = await pg.query(`select property_json::json from setting.property
58
+ where property_entity='column' and object_id=$1`, [table]).then(el => el.rows?.[0] || {});
59
+
60
+ const columns = (tableSettingColumns || loadTable?.columns || meta?.columns)?.map((el) => ({ ...el, title: el.title || el.name }))
61
+ ?.filter((value, index, array) => array?.map((el) => el.name).indexOf(value.name) === index); // get unique columns
62
+
63
+ const cls = columns?.filter((el) => ['badge', 'select'].includes(el.format) && (el.option || el.data))
64
+ ?.map((el) => (el.option || el.data))
65
+ ?.filter((value, index, array) => array.indexOf(value) === index); // get unique cls
66
+
67
+ const { property_json: userFilterList } = await pg.query(`select property_json::json from setting.property
68
+ where property_entity='filter' and object_id=$1`, [table]).then(el => el.rows?.[0] || {});
69
+
70
+ const { property_json: customQuery } = await pg.query(`select json_agg(json_build_object('id',property_id,'name', property_key,
71
+ 'query', property_text, 'disabled', coalesce((property_json::json->>'disabled')::boolean,false) )) as property_json
72
+ from setting.property where 1=1 and property_entity='customQuery' and object_id=$1`, [table]).then(el => el.rows?.[0] || {});
73
+
74
+ time.push(Date.now());
75
+
76
+ const debug = user?.user_type?.includes('admin') && query?.debug
77
+ ? {
78
+ view,
79
+ tableName,
80
+ metaColumns: meta?.columns,
81
+ columnProperties: tableSettingColumns,
82
+ }
83
+ : undefined;
84
+
85
+ const res = {
86
+ time: {
87
+ geom: time[1] - time[0],
88
+ stat: time[2] - time[1],
89
+ count: time[3] - time[2],
90
+ total: time[4] - time[0],
91
+ },
92
+ debug,
93
+ model: tableName,
94
+ total,
95
+ geometry,
96
+ stat,
97
+ cls,
98
+ columns,
99
+ filters: userFilterList?.length
100
+ ? userFilterList
101
+ : loadTable?.filters?.map((el) => ({ ...el, title: el.title || el.ua })),
102
+ customQuery: customQuery?.length ? customQuery : [],
103
+ customColumns,
104
+ customFilters: userFilterList || [],
105
+ };
106
+
107
+ if (entity) {
108
+ return reply.status(200).send({ [entity]: res[entity] });
109
+ }
110
+
111
+ return reply.status(200).send(res);
112
+ }
@@ -0,0 +1,121 @@
1
+ import { pgClients, getRedis } from '../../../../utils.js';
2
+
3
+ import refreshData from '../utils/refreshData.js';
4
+
5
+ const rclient = getRedis();
6
+
7
+ /**
8
+ *
9
+ * @method POST
10
+ * @priority 4
11
+ * @alias postSettingsTable
12
+ * @type api
13
+ * @tag custom
14
+ * @returns {String} message and status
15
+ */
16
+
17
+ export default async function postTablpostSettingsTableeProperties({
18
+ pg = pgClients.client, params = {}, body = {}, user = {},
19
+ }, reply) {
20
+ const { table } = params;
21
+ const { uid } = user;
22
+
23
+ if (!uid) {
24
+ return reply.status(401).send('unauthorized');
25
+ }
26
+
27
+ if (!table) {
28
+ return reply.status(400).send('not enough params: table');
29
+ }
30
+
31
+ const {
32
+ deleted = [],
33
+ columns = [],
34
+ filters = [],
35
+ customColumns = [],
36
+ customQuery = [],
37
+ } = body;
38
+
39
+ const cacheKey = `${pg.options?.database}:filter-list:${table}`;
40
+
41
+ if (Array.isArray(deleted) && deleted?.length) {
42
+ const sqlList = {
43
+ columns: 'delete from setting.property where property_entity=\'column\' and object_id=$1',
44
+ filters: 'delete from setting.property where property_entity=\'filter\' and object_id=$1',
45
+ customColumns: `delete from setting.custom_data where attr in (select cf_id from setting.custom_field where object_id=$1);
46
+ delete from setting.custom_field where object_id=$1;
47
+ delete from setting.property where property_entity='customColumn' and object_id=$1;`,
48
+ customQuery: 'delete from setting.property where property_entity=\'customQuery\' and object_id=$1;',
49
+ };
50
+ const q = deleted.map((item) => sqlList[item])?.filter((el) => el)?.join(' ');
51
+ const { rowCount = 0 } = await pg.query(q, [table]);
52
+
53
+ if (['customColumn', 'column'].find((el) => deleted.includes(el))) {
54
+ // await funcs.applyHook('preTemplate', { pg, name: table, type: 'table' });
55
+ }
56
+ if (['customQuery', 'filter'].find((el) => deleted.includes(el))) {
57
+ await rclient.del(cacheKey);
58
+ }
59
+
60
+ if (rowCount === 0) {
61
+ return reply.status(200).send('nothing to restore');
62
+ }
63
+
64
+ return reply.status(200).send({
65
+ command: 'DELETE',
66
+ deleted,
67
+ table,
68
+ result: 'success',
69
+ });
70
+ }
71
+
72
+ const result = {};
73
+ // custom filter query (sql)
74
+ if (customQuery?.length) {
75
+ const res = await refreshData({
76
+ pg, entity: 'customQuery', table, uid, data: customQuery,
77
+ });
78
+ if (res?.error) return res;
79
+ Object.assign(result, { customQuery: res });
80
+ }
81
+
82
+ // columns
83
+ if (columns?.length) {
84
+ const res = await refreshData({
85
+ pg, entity: 'column', table, uid, data: columns,
86
+ });
87
+ if (res?.error) return res;
88
+ Object.assign(result, { columns: res });
89
+ }
90
+
91
+ // custom columns
92
+ if (customColumns?.length) {
93
+ const colModel = await pg.query(`select property_json::json from setting.property
94
+ where property_entity='customColumn' and object_id=$1`, [table]).then((el) => el.rows?.[0]?.property_json);
95
+
96
+ const res = await refreshData({
97
+ pg, entity: 'customColumn', table, uid, data: customColumns, colModel,
98
+ });
99
+ if (res?.error) return res;
100
+ Object.assign(result, { customColumns: res });
101
+ }
102
+
103
+ // filters
104
+ if (filters?.length) {
105
+ const res = await refreshData({
106
+ pg, entity: 'filter', table, uid, data: filters,
107
+ });
108
+ if (res?.error) return res;
109
+
110
+ Object.assign(result, { filters: res });
111
+ }
112
+
113
+ if (columns?.length || customColumns?.length) {
114
+ // await funcs.applyHook('preTemplate', { pg, type: 'table', name: table });
115
+ }
116
+ if (filters?.length || customQuery?.length) {
117
+ await rclient.del(cacheKey);
118
+ }
119
+
120
+ return reply.status(200).send(result);
121
+ }
@@ -1,11 +1,21 @@
1
1
  import getExtraProperties from './controllers/properties.get.js';
2
2
  import addExtraProperties from './controllers/properties.add.js';
3
3
 
4
+ import getSettingsApp from './controllers/admin.properties.get.js';
5
+ import postSettingsApp from './controllers/admin.properties.post.js';
6
+
7
+ import getSettingsTable from './controllers/table.properties.get.js';
8
+ import postSettingsTable from './controllers/table.properties.post.js';
9
+
4
10
  const propertiesSchema = {
5
11
  type: 'object',
6
- properties: {
12
+ properties: {
7
13
  params: {
8
14
  id: { type: 'string', pattern: '^([\\d\\w]+)$' },
15
+ key: { type: 'string', pattern: '^([\\d\\w._]+)$' },
16
+ },
17
+ querystring: {
18
+ json: { type: 'string', pattern: '^([\\d\\w]+)$' },
9
19
  },
10
20
  },
11
21
  };
@@ -14,6 +24,12 @@ async function plugin(app, config = {}) {
14
24
  const { prefix = '/api' } = config;
15
25
  app.get(`${prefix}/properties/:id`, { schema: propertiesSchema }, getExtraProperties);
16
26
  app.post(`${prefix}/properties/:id`, { schema: propertiesSchema }, addExtraProperties);
27
+
28
+ app.get(`${prefix}/settings-app/:key?`, { scheme: propertiesSchema }, getSettingsApp);
29
+ app.post(`${prefix}/settings-app`, { config: { policy: ['admin'] } }, postSettingsApp);
30
+
31
+ app.get(`${prefix}/settings-table/:table/:entity?`, {}, getSettingsTable);
32
+ app.post(`${prefix}/settings-table/:table`, {}, postSettingsTable);
17
33
  }
18
34
 
19
35
  export default plugin;
@@ -0,0 +1,26 @@
1
+ import { getMeta, getPG } from '../../../../utils.js';
2
+
3
+ export default async function dataInsert({
4
+ table, data, pg: pg1,
5
+ }) {
6
+ const pg = pg1 || getPG({ name: 'client' });
7
+ if (!data) return null;
8
+ const { columns } = await getMeta(table);
9
+ if (!columns) return null;
10
+
11
+ const names = columns.map((el) => el.name);
12
+ const filterData = Object.keys(data)
13
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
14
+
15
+ const insertQuery = `insert into ${table}
16
+
17
+ ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
18
+
19
+ values (${filterData?.map((key, i) => (key[0] === 'property_json' ? `to_json($${i + 1}::${key[1] && typeof key[1] === 'object' ? 'json' : 'text'})` : `$${i + 1}`)).join(',')})
20
+
21
+ returning *`;
22
+
23
+ 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]))]) || {};
24
+
25
+ return res;
26
+ }
@@ -0,0 +1,19 @@
1
+ import { pgClients, getMeta } from '../../../../utils.js';
2
+
3
+ const systemColumns = ['files', 'uid', 'editor_date', 'editor_id', 'cdate', 'created_at', 'updated_at', 'created_by', 'updated_by'];
4
+
5
+ export default async function getColumnMetaData({
6
+ pg = pgClients.client, table,
7
+ }) {
8
+ if (!table) return null;
9
+
10
+ const { columns = [] } = await getMeta({ pg, table });
11
+ const columnList = columns.filter(el => !systemColumns.includes(el.name)).map(el => el.name);
12
+
13
+ const sql = `select count(*) as total, ${columnList.map((item) => `(count(*) filter(where ${item} is not null)) as "${item}"`).join(',')} from ${table}`;
14
+ const res = await pg.queryCache(sql, { table }).then(el => el.rows?.[0] || {});
15
+
16
+ return columns
17
+ .filter(el => !systemColumns.includes(el.name))
18
+ .map((row) => Object.assign(row, { percent: ((+res[row.name] / +res.total) * 100).toFixed(0) }));
19
+ }
@@ -0,0 +1,129 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+
3
+ import { dataInsert, pgClients } from '../../../../utils.js';
4
+
5
+ function prepareResult(res) {
6
+ const arr = (res.rows || (Array.isArray(res) ? res : Object.values(res || {})));
7
+ return {
8
+ command: 'INSERT',
9
+ count: res?.rowCount || arr.filter((el) => el.command === 'INSERT')
10
+ ?.map((el) => ({ result: 'success', count: el.rowCount }))
11
+ ?.reduce((acc, curr) => acc + curr.count, 0),
12
+ };
13
+ }
14
+
15
+ export default async function refreshData({
16
+ pg = pgClients.client, entity, table, uid, data,
17
+ }) {
18
+ if (!['filter', 'column', 'customQuery', 'customColumn'].includes(entity)) {
19
+ return { message: 'invalid params: entity', status: 400 };
20
+ }
21
+
22
+ const client = await pg.connect();
23
+
24
+ /* getMeta support */
25
+ client.options = pg.options;
26
+ client.tlist = pg.tlist;
27
+ client.pgType = pg.pgType;
28
+ client.pk = pg.pk;
29
+ client.relkinds = pg.relkinds;
30
+
31
+ const result = {};
32
+
33
+ try {
34
+ await client.query('BEGIN');
35
+
36
+ if (['filter', 'column'].includes(entity)) {
37
+ data?.forEach((el) => Object.assign(el, { id: el.id || randomUUID() }));
38
+ await client.query('delete from setting.property where object_id=$1 and property_entity=$2', [table, entity]);
39
+
40
+ const res = await dataInsert({
41
+ pg: client,
42
+ table: 'setting.property',
43
+ data: {
44
+ property_entity: entity,
45
+ object_id: table,
46
+ property_json: JSON.stringify(data), // ?.replace(/'+/g, "'")?.replace(/'/g, "''")
47
+ },
48
+ uid,
49
+ });
50
+ Object.assign(result, res);
51
+ }
52
+
53
+ if (['customQuery'].includes(entity)) {
54
+ await client.query('delete from setting.property where object_id=$1 and property_entity=$2', [table, entity]);
55
+
56
+ const res = await Promise.all(data?.map(async (el) => dataInsert({
57
+ pg: client,
58
+ table: 'setting.property',
59
+ data: {
60
+ property_entity: entity,
61
+ object_id: table,
62
+ property_key: el.name,
63
+ property_text: el.query,
64
+ property_json: { disabled: el.disabled },
65
+ },
66
+ uid,
67
+ })));
68
+ Object.assign(result, res);
69
+ }
70
+
71
+ if (entity === 'customColumn') {
72
+ const prefix = createHash('md5').update(table).digest('hex').substr(0, 10);
73
+ const data1 = [];
74
+
75
+ await Promise.all(data.map(async (el, index) => {
76
+ const obj = {
77
+ cf_id: `col_${prefix}_${index}`,
78
+ cf_name: el.title || el.ua || el.name,
79
+ cf_type: el.format || el.type,
80
+ cf_default: el.default,
81
+ cf_notnull: el.notnull,
82
+ object_id: table,
83
+ tablename: table,
84
+ };
85
+
86
+ data1.push({
87
+ name: obj.cf_id,
88
+ title: obj.cf_name,
89
+ format: obj.cf_type,
90
+ option: data[index]?.option,
91
+ hidden: data[index]?.hidden,
92
+ custom: true,
93
+ });
94
+
95
+ await dataInsert({
96
+ pg: client,
97
+ table: 'setting.custom_field',
98
+ data: obj,
99
+ uid,
100
+ });
101
+ }));
102
+
103
+ await client.query('delete from setting.custom_field where $1 in (tablename, object_id)', [table]);
104
+ await client.query('delete from setting.property where object_id=$1 and property_entity=$2', [table, entity]);
105
+
106
+ const data2 = JSON.stringify(data1?.filter((value, index, array) => array.indexOf(value) === index)); // ?.replace(/'+/g, "'")?.replace(/'/g, "''")
107
+ const res = await dataInsert({
108
+ pg: client,
109
+ table: 'setting.property',
110
+ data: {
111
+ property_entity: 'customColumn',
112
+ object_id: table,
113
+ property_json: data2,
114
+ },
115
+ uid,
116
+ });
117
+ Object.assign(result, res);
118
+ }
119
+ await client.query('COMMIT');
120
+ return prepareResult(result);
121
+ }
122
+ catch (err) {
123
+ await client.query('ROLLBACK');
124
+ return { error: err.toString(), status: 500 };
125
+ }
126
+ finally {
127
+ client.release();
128
+ }
129
+ }