@opengis/fastify-table 1.2.70 → 1.2.71

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 (43) hide show
  1. package/README.md +86 -86
  2. package/package.json +1 -1
  3. package/server/migrations/cls.sql +39 -39
  4. package/server/plugins/cron/funcs/addCron.js +130 -130
  5. package/server/plugins/cron/index.js +6 -6
  6. package/server/plugins/crud/funcs/getOpt.js +13 -13
  7. package/server/plugins/crud/funcs/setOpt.js +21 -21
  8. package/server/plugins/crud/funcs/setToken.js +44 -44
  9. package/server/plugins/crud/funcs/utils/getFolder.js +11 -11
  10. package/server/plugins/crud/index.js +23 -23
  11. package/server/plugins/hook/index.js +8 -8
  12. package/server/plugins/logger/errorStatus.js +19 -19
  13. package/server/plugins/logger/index.js +26 -26
  14. package/server/plugins/migration/index.js +7 -7
  15. package/server/plugins/policy/sqlInjection.js +33 -33
  16. package/server/plugins/redis/client.js +8 -8
  17. package/server/plugins/redis/funcs/redisClients.js +3 -3
  18. package/server/plugins/redis/index.js +17 -17
  19. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  20. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  21. package/server/plugins/table/funcs/getTemplates.js +19 -19
  22. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  23. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  24. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  25. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  26. package/server/plugins/table/index.js +13 -13
  27. package/server/plugins/util/index.js +7 -7
  28. package/server/routes/cron/index.js +14 -14
  29. package/server/routes/logger/controllers/logger.file.js +92 -92
  30. package/server/routes/logger/controllers/utils/checkUserAccess.js +19 -19
  31. package/server/routes/logger/controllers/utils/getRootDir.js +26 -26
  32. package/server/routes/logger/index.js +17 -17
  33. package/server/routes/properties/controllers/properties.add.js +55 -55
  34. package/server/routes/properties/controllers/properties.get.js +17 -17
  35. package/server/routes/properties/index.js +16 -16
  36. package/server/routes/table/controllers/data.js +2 -1
  37. package/server/routes/table/controllers/filter.js +6 -23
  38. package/server/routes/table/controllers/form.js +42 -42
  39. package/server/routes/table/controllers/search.js +74 -74
  40. package/server/routes/table/index.js +29 -29
  41. package/server/routes/table/schema.js +64 -64
  42. package/server/routes/util/controllers/status.monitor.js +8 -8
  43. package/server/routes/util/index.js +11 -11
@@ -1,82 +1,82 @@
1
- import getSelect from './getSelect.js';
2
-
3
- import getFilterSQL from './getFilterSQL/index.js';
4
- import getTemplate from './getTemplate.js';
5
- import pgClients from '../../pg/pgClients.js';
6
- import config from '../../../../config.js';
7
- import getSelectVal from './metaFormat/getSelectVal.js';
8
-
9
- export default async function gisIRColumn({
10
- pg = pgClients.client, layer, column, sql, query = '1=1', filter, state, search, custom,
11
- }) {
12
- const time = Date.now();
13
-
14
- const sel = await getSelect(query.cls || column, pg);
15
-
16
- const body = await getTemplate('table', layer);
17
- const fData = await getFilterSQL({
18
- table: layer,
19
- filter,
20
- state,
21
- search,
22
- custom,
23
- });
24
-
25
- const { tlist } = await pg.one(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist from pg_class
26
- where relkind in ('r','v','m')`);
27
-
28
- const tableName = body?.table || layer;
29
- if (!tlist.includes(tableName)) return { error: `table not found: ${tableName}`, status: 400 };
30
-
31
- // eslint-disable-next-line max-len
32
- const { fields } = await pg.query(`select * from (${fData?.optimizedSQL || `select * from ${tableName}`})q limit 0`);
33
-
34
- const col = fields.find((el) => el.name === column);
35
-
36
- if (!col) return { status: 404, message: 'not found' };
37
- const colField = pg.pgType[col.dataTypeID]?.includes('[]') ? `unnest(${column})` : column;
38
-
39
- const q = `select ${colField} as id, count(*)::int from (
40
- ${fData?.optimizedSQL || `select * from ${tableName} where ${body?.query || 'true'}`}
41
- )t group by ${colField} order by count desc limit 15`;
42
-
43
- if (sql) return q;
44
-
45
- if (!body?.columns?.length) {
46
- const { rows } = await pg.query(q);
47
- if (sel?.arr?.length) {
48
- rows.forEach((el) => {
49
- const data = sel?.find((item) => item.id?.toString() === el.id?.toString());
50
- Object.assign(el, data || {});
51
- });
52
- }
53
- return {
54
- count: rows?.reduce((acc, el) => acc + el.count, 0),
55
- sql: config.local ? q : undefined,
56
- rows,
57
- };
58
- }
59
-
60
- const { rows } = await pg.query(q);
61
- const cls = query.cls || body?.columns?.find((el) => el.name === column)?.data || col.data || col.option;
62
- const select = await getSelectVal({
63
- pg, name: cls, values: rows.map((el) => el.id), ar: 1,
64
- });
65
- rows.forEach((el) => {
66
- if (Array.isArray(select)) {
67
- Object.assign(el, select.find((item) => item.id?.toString() === el.id?.toString()) || {});
68
- }
69
- else if (typeof select?.[el.id] === 'string') {
70
- Object.assign(el, { text: select?.[el.id] });
71
- }
72
- else {
73
- Object.assign(el, select?.[el.id] || {});
74
- }
75
- });
76
- return {
77
- time: Date.now() - time,
78
- count: rows.reduce((acc, el) => acc + el.count, 0),
79
- sql: config.local ? q : undefined,
80
- rows,
81
- };
82
- }
1
+ import getSelect from './getSelect.js';
2
+
3
+ import getFilterSQL from './getFilterSQL/index.js';
4
+ import getTemplate from './getTemplate.js';
5
+ import pgClients from '../../pg/pgClients.js';
6
+ import config from '../../../../config.js';
7
+ import getSelectVal from './metaFormat/getSelectVal.js';
8
+
9
+ export default async function gisIRColumn({
10
+ pg = pgClients.client, layer, column, sql, query = '1=1', filter, state, search, custom,
11
+ }) {
12
+ const time = Date.now();
13
+
14
+ const sel = await getSelect(query.cls || column, pg);
15
+
16
+ const body = await getTemplate('table', layer);
17
+ const fData = await getFilterSQL({
18
+ table: layer,
19
+ filter,
20
+ state,
21
+ search,
22
+ custom,
23
+ });
24
+
25
+ const { tlist } = await pg.one(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist from pg_class
26
+ where relkind in ('r','v','m')`);
27
+
28
+ const tableName = body?.table || layer;
29
+ if (!tlist.includes(tableName)) return { error: `table not found: ${tableName}`, status: 400 };
30
+
31
+ // eslint-disable-next-line max-len
32
+ const { fields } = await pg.query(`select * from (${fData?.optimizedSQL || `select * from ${tableName}`})q limit 0`);
33
+
34
+ const col = fields.find((el) => el.name === column);
35
+
36
+ if (!col) return { status: 404, message: 'not found' };
37
+ const colField = pg.pgType[col.dataTypeID]?.includes('[]') ? `unnest(${column})` : column;
38
+
39
+ const q = `select ${colField} as id, count(*)::int from (
40
+ ${fData?.optimizedSQL || `select * from ${tableName} where ${body?.query || 'true'}`}
41
+ )t group by ${colField} order by count desc limit 15`;
42
+
43
+ if (sql) return q;
44
+
45
+ if (!body?.columns?.length) {
46
+ const { rows } = await pg.query(q);
47
+ if (sel?.arr?.length) {
48
+ rows.forEach((el) => {
49
+ const data = sel?.find((item) => item.id?.toString() === el.id?.toString());
50
+ Object.assign(el, data || {});
51
+ });
52
+ }
53
+ return {
54
+ count: rows?.reduce((acc, el) => acc + el.count, 0),
55
+ sql: config.local ? q : undefined,
56
+ rows,
57
+ };
58
+ }
59
+
60
+ const { rows } = await pg.query(q);
61
+ const cls = query.cls || body?.columns?.find((el) => el.name === column)?.data || col.data || col.option;
62
+ const select = await getSelectVal({
63
+ pg, name: cls, values: rows.map((el) => el.id), ar: 1,
64
+ });
65
+ rows.forEach((el) => {
66
+ if (Array.isArray(select)) {
67
+ Object.assign(el, select.find((item) => item.id?.toString() === el.id?.toString()) || {});
68
+ }
69
+ else if (typeof select?.[el.id] === 'string') {
70
+ Object.assign(el, { text: select?.[el.id] });
71
+ }
72
+ else {
73
+ Object.assign(el, select?.[el.id] || {});
74
+ }
75
+ });
76
+ return {
77
+ time: Date.now() - time,
78
+ count: rows.reduce((acc, el) => acc + el.count, 0),
79
+ sql: config.local ? q : undefined,
80
+ rows,
81
+ };
82
+ }
@@ -1 +1 @@
1
- export default {};
1
+ export default {};
@@ -1 +1 @@
1
- export default {};
1
+ export default {};
@@ -1 +1 @@
1
- export default [];
1
+ export default [];
@@ -1,13 +1,13 @@
1
- import metaFormat from './funcs/metaFormat/index.js';
2
- import getFilterSQL from './funcs/getFilterSQL/index.js';
3
- import getTemplate from './funcs/getTemplate.js';
4
- import getSelect from './funcs/getSelect.js';
5
-
6
- async function plugin(fastify) {
7
- // fastify.decorate('metaFormat', metaFormat);
8
- // fastify.decorate('getFilterSQL', getFilterSQL);
9
- // fastify.decorate('getTemplate', getTemplate);
10
- // fastify.decorate('getSelect', getSelect);
11
- }
12
-
13
- export default plugin;
1
+ import metaFormat from './funcs/metaFormat/index.js';
2
+ import getFilterSQL from './funcs/getFilterSQL/index.js';
3
+ import getTemplate from './funcs/getTemplate.js';
4
+ import getSelect from './funcs/getSelect.js';
5
+
6
+ async function plugin(fastify) {
7
+ // fastify.decorate('metaFormat', metaFormat);
8
+ // fastify.decorate('getFilterSQL', getFilterSQL);
9
+ // fastify.decorate('getTemplate', getTemplate);
10
+ // fastify.decorate('getSelect', getSelect);
11
+ }
12
+
13
+ export default plugin;
@@ -1,7 +1,7 @@
1
- import eventStream from './funcs/eventStream.js';
2
-
3
- async function plugin(fastify) {
4
- // fastify.decorate('eventStream', eventStream);
5
- }
6
-
7
- export default plugin;
1
+ import eventStream from './funcs/eventStream.js';
2
+
3
+ async function plugin(fastify) {
4
+ // fastify.decorate('eventStream', eventStream);
5
+ }
6
+
7
+ export default plugin;
@@ -1,14 +1,14 @@
1
- import cronApi from './controllers/cronApi.js';
2
-
3
- const cronSchema = {
4
- params: {
5
- name: { type: 'string', pattern: '^([\\d\\w._-]+)$' },
6
- },
7
- };
8
-
9
- async function plugin(fastify, config = {}) {
10
- const prefix = config.prefix || '/api';
11
- fastify.get(`${prefix}/cron/:name`, { schema: cronSchema }, cronApi);
12
- }
13
-
14
- export default plugin;
1
+ import cronApi from './controllers/cronApi.js';
2
+
3
+ const cronSchema = {
4
+ params: {
5
+ name: { type: 'string', pattern: '^([\\d\\w._-]+)$' },
6
+ },
7
+ };
8
+
9
+ async function plugin(fastify, config = {}) {
10
+ const prefix = config.prefix || '/api';
11
+ fastify.get(`${prefix}/cron/:name`, { schema: cronSchema }, cronApi);
12
+ }
13
+
14
+ export default plugin;
@@ -1,92 +1,92 @@
1
- import path from 'node:path';
2
- import { lstat, readdir, readFile } from 'node:fs/promises';
3
- import { createReadStream, existsSync } from 'node:fs';
4
- import readline from 'node:readline';
5
-
6
- import checkUserAccess from './utils/checkUserAccess.js';
7
- import getRootDir from './utils/getRootDir.js';
8
-
9
- /**
10
- *
11
- * @method GET
12
- * @summary API для перегляду логів
13
- *
14
- */
15
-
16
- export default async function loggerFile({
17
- params = {}, user = {}, query = {}, originalUrl,
18
- }, reply) {
19
- const limit = 200000;
20
- // console.log(user);
21
- const access = checkUserAccess({ user });
22
- // log.info('Сервер запущен по адресу?'); // test!
23
-
24
- if (access?.status !== 200) return access;
25
-
26
- // absolute / relative path
27
- const rootDir = getRootDir();
28
-
29
- const filepath = path.join(rootDir, params['*'] || '');
30
-
31
- if (!existsSync(filepath)) {
32
- return { message: 'file not exists', status: 404 };
33
- }
34
- const stat = await lstat(filepath);
35
- const isFile = stat.isFile();
36
-
37
- if (query.download && isFile) {
38
- return reply.download(filepath);
39
- }
40
-
41
- if (query.full && isFile) {
42
- if (stat.size > 20 * 1000 * 1000) {
43
- return { message: 'file size > 20MB' };
44
- }
45
- const buffer = await readFile(filepath, { buffer: true });
46
- return buffer;
47
- }
48
-
49
- if (isFile) {
50
- const ext = path.extname(filepath);
51
-
52
- const lines = await new Promise((resolve) => {
53
- const rl = readline.createInterface({
54
- input: createReadStream(filepath, { start: stat.size > limit ? stat.size - limit : 0 }),
55
- });
56
- const lines1 = [];
57
- rl.on('close', () => resolve(lines1));
58
- rl.on('line', (line) => lines1.push(line));
59
- });
60
-
61
- if (ext === '.html') {
62
- const buffer = await readFile(filepath, { buffer: true });
63
- reply.headers({ 'Content-type': 'text/html; charset=UTF-8' });
64
- return buffer;
65
- }
66
-
67
- reply.headers({ 'Content-type': 'text/plain; charset=UTF-8' });
68
- return stat.size > limit && lines.length > 1
69
- ? lines.reverse().slice(0, -1).join('\n')
70
- : lines.reverse().join('\n');
71
- }
72
-
73
- // dir
74
- const files = await readdir(filepath);
75
-
76
- if (query.dir) {
77
- return files.filter((el) => !['backup', 'marker_icon', 'error', 'migration'].includes(el));
78
- }
79
-
80
- const lstatsArr = await Promise.all(files.map(async (file) => [file, await lstat(path.join(filepath, file))]));
81
- const lstats = Object.fromEntries(lstatsArr);
82
-
83
- const message = (params['*'] ? '<a href="/logger-file/">...</a><br>' : '')
84
- + files.map((file) => `<a href="${originalUrl}/${file}">${file}</a> (${lstats[file].size} bytes)`).join('</br>');
85
-
86
- reply.headers({
87
- 'Content-Type': 'text/html; charset=UTF-8',
88
- 'Content-Security-Policy': "default-src 'none'",
89
- 'X-Content-Type-Options': 'nosniff',
90
- });
91
- return message;
92
- }
1
+ import path from 'node:path';
2
+ import { lstat, readdir, readFile } from 'node:fs/promises';
3
+ import { createReadStream, existsSync } from 'node:fs';
4
+ import readline from 'node:readline';
5
+
6
+ import checkUserAccess from './utils/checkUserAccess.js';
7
+ import getRootDir from './utils/getRootDir.js';
8
+
9
+ /**
10
+ *
11
+ * @method GET
12
+ * @summary API для перегляду логів
13
+ *
14
+ */
15
+
16
+ export default async function loggerFile({
17
+ params = {}, user = {}, query = {}, originalUrl,
18
+ }, reply) {
19
+ const limit = 200000;
20
+ // console.log(user);
21
+ const access = checkUserAccess({ user });
22
+ // log.info('Сервер запущен по адресу?'); // test!
23
+
24
+ if (access?.status !== 200) return access;
25
+
26
+ // absolute / relative path
27
+ const rootDir = getRootDir();
28
+
29
+ const filepath = path.join(rootDir, params['*'] || '');
30
+
31
+ if (!existsSync(filepath)) {
32
+ return { message: 'file not exists', status: 404 };
33
+ }
34
+ const stat = await lstat(filepath);
35
+ const isFile = stat.isFile();
36
+
37
+ if (query.download && isFile) {
38
+ return reply.download(filepath);
39
+ }
40
+
41
+ if (query.full && isFile) {
42
+ if (stat.size > 20 * 1000 * 1000) {
43
+ return { message: 'file size > 20MB' };
44
+ }
45
+ const buffer = await readFile(filepath, { buffer: true });
46
+ return buffer;
47
+ }
48
+
49
+ if (isFile) {
50
+ const ext = path.extname(filepath);
51
+
52
+ const lines = await new Promise((resolve) => {
53
+ const rl = readline.createInterface({
54
+ input: createReadStream(filepath, { start: stat.size > limit ? stat.size - limit : 0 }),
55
+ });
56
+ const lines1 = [];
57
+ rl.on('close', () => resolve(lines1));
58
+ rl.on('line', (line) => lines1.push(line));
59
+ });
60
+
61
+ if (ext === '.html') {
62
+ const buffer = await readFile(filepath, { buffer: true });
63
+ reply.headers({ 'Content-type': 'text/html; charset=UTF-8' });
64
+ return buffer;
65
+ }
66
+
67
+ reply.headers({ 'Content-type': 'text/plain; charset=UTF-8' });
68
+ return stat.size > limit && lines.length > 1
69
+ ? lines.reverse().slice(0, -1).join('\n')
70
+ : lines.reverse().join('\n');
71
+ }
72
+
73
+ // dir
74
+ const files = await readdir(filepath);
75
+
76
+ if (query.dir) {
77
+ return files.filter((el) => !['backup', 'marker_icon', 'error', 'migration'].includes(el));
78
+ }
79
+
80
+ const lstatsArr = await Promise.all(files.map(async (file) => [file, await lstat(path.join(filepath, file))]));
81
+ const lstats = Object.fromEntries(lstatsArr);
82
+
83
+ const message = (params['*'] ? '<a href="/logger-file/">...</a><br>' : '')
84
+ + files.map((file) => `<a href="${originalUrl}/${file}">${file}</a> (${lstats[file].size} bytes)`).join('</br>');
85
+
86
+ reply.headers({
87
+ 'Content-Type': 'text/html; charset=UTF-8',
88
+ 'Content-Security-Policy': "default-src 'none'",
89
+ 'X-Content-Type-Options': 'nosniff',
90
+ });
91
+ return message;
92
+ }
@@ -1,19 +1,19 @@
1
- import config from '../../../../../config.js';
2
-
3
- /**
4
- *
5
- * @summary check user access to logger interface - per admin user type or user group
6
- * @returns {Object} message, status
7
- */
8
-
9
- export default function checkUserAccess({ user = {} }) {
10
- // console.log(user);
11
- if (user.user_type !== 'admin' && !config?.local) {
12
- return { message: 'access restricted', status: 403 };
13
- }
14
-
15
- /* if (!['admin', 'superadmin']?.includes(user.user_type) && count === '0') {
16
- return { message: 'access restricted', status: 403 };
17
- } */
18
- return { message: 'access granted', status: 200 };
19
- }
1
+ import config from '../../../../../config.js';
2
+
3
+ /**
4
+ *
5
+ * @summary check user access to logger interface - per admin user type or user group
6
+ * @returns {Object} message, status
7
+ */
8
+
9
+ export default function checkUserAccess({ user = {} }) {
10
+ // console.log(user);
11
+ if (user.user_type !== 'admin' && !config?.local) {
12
+ return { message: 'access restricted', status: 403 };
13
+ }
14
+
15
+ /* if (!['admin', 'superadmin']?.includes(user.user_type) && count === '0') {
16
+ return { message: 'access restricted', status: 403 };
17
+ } */
18
+ return { message: 'access granted', status: 200 };
19
+ }
@@ -1,26 +1,26 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- import config from '../../../../../config.js';
5
-
6
- // import { existsSync } from 'fs';
7
- let logDir = null;
8
- export default function getRootDir() {
9
- // absolute / relative path
10
- if (logDir) return logDir;
11
- const file = ['config.json', '/data/local/config.json'].find(el => (fs.existsSync(el) ? el : null));
12
- const root = file === 'config.json' ? process.cwd() : '/data/local';
13
- logDir = config.logDir || path.join(root, config.log?.dir || 'log');
14
- console.log({ logDir });
15
- return logDir;
16
-
17
- // windows debug support
18
- /* const customLogDir = process.cwd().includes(':') ? 'c:/data/local' : '/data/local';
19
- // docker default path
20
- if (existsSync(customLogDir)) {
21
- return path.join(customLogDir, config.folder || '', 'log');
22
- }
23
-
24
- // non-docker default path
25
- return path.join(config.root || '/data/local', config.folder || '', 'log'); */
26
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import config from '../../../../../config.js';
5
+
6
+ // import { existsSync } from 'fs';
7
+ let logDir = null;
8
+ export default function getRootDir() {
9
+ // absolute / relative path
10
+ if (logDir) return logDir;
11
+ const file = ['config.json', '/data/local/config.json'].find(el => (fs.existsSync(el) ? el : null));
12
+ const root = file === 'config.json' ? process.cwd() : '/data/local';
13
+ logDir = config.logDir || path.join(root, config.log?.dir || 'log');
14
+ console.log({ logDir });
15
+ return logDir;
16
+
17
+ // windows debug support
18
+ /* const customLogDir = process.cwd().includes(':') ? 'c:/data/local' : '/data/local';
19
+ // docker default path
20
+ if (existsSync(customLogDir)) {
21
+ return path.join(customLogDir, config.folder || '', 'log');
22
+ }
23
+
24
+ // non-docker default path
25
+ return path.join(config.root || '/data/local', config.folder || '', 'log'); */
26
+ }
@@ -1,17 +1,17 @@
1
- import loggerFile from './controllers/logger.file.js';
2
-
3
- // import loggerTest from './controllers/logger.test.api.js';
4
-
5
- const loggerSchema = {
6
- querystring: {
7
- download: { type: 'string', pattern: '^(\\d+)$' },
8
- full: { type: 'string', pattern: '^(\\d+)$' },
9
- dir: { type: 'string', pattern: '^(\\d+)$' },
10
- },
11
- };
12
-
13
- async function plugin(fastify) {
14
- fastify.get('/logger-file/*', { config: { policy: ['site'] }, schema: loggerSchema }, loggerFile);
15
- }
16
-
17
- export default plugin;
1
+ import loggerFile from './controllers/logger.file.js';
2
+
3
+ // import loggerTest from './controllers/logger.test.api.js';
4
+
5
+ const loggerSchema = {
6
+ querystring: {
7
+ download: { type: 'string', pattern: '^(\\d+)$' },
8
+ full: { type: 'string', pattern: '^(\\d+)$' },
9
+ dir: { type: 'string', pattern: '^(\\d+)$' },
10
+ },
11
+ };
12
+
13
+ async function plugin(fastify) {
14
+ fastify.get('/logger-file/*', { config: { policy: ['site'] }, schema: loggerSchema }, loggerFile);
15
+ }
16
+
17
+ export default plugin;