@opengis/fastify-table 1.4.82 → 1.4.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/index.js +30 -9
  2. package/package.json +2 -2
  3. package/server/helpers/core/token.js +18 -18
  4. package/server/plugins/cron/funcs/addCron.js +52 -52
  5. package/server/plugins/crud/funcs/dataDelete.js +2 -2
  6. package/server/plugins/crud/funcs/getOpt.js +14 -14
  7. package/server/plugins/crud/funcs/utils/getFolder.js +11 -11
  8. package/server/plugins/logger/errorStatus.js +19 -19
  9. package/server/plugins/pg/funcs/init.js +2 -2
  10. package/server/plugins/redis/client.js +8 -8
  11. package/server/plugins/redis/funcs/redisClients.js +3 -3
  12. package/server/plugins/sqlite/funcs/getSqlite.js +8 -3
  13. package/server/plugins/sqlite/funcs/init.js +1 -1
  14. package/server/plugins/sqlite/sqliteClients.js +8 -3
  15. package/server/plugins/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  16. package/server/plugins/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  17. package/server/plugins/table/funcs/getTemplates.js +19 -19
  18. package/server/plugins/table/funcs/gisIRColumn.js +82 -82
  19. package/server/plugins/table/funcs/loadTemplate.js +1 -1
  20. package/server/plugins/table/funcs/loadTemplatePath.js +1 -1
  21. package/server/plugins/table/funcs/userTemplateDir.js +1 -1
  22. package/server/plugins/util/funcs/unflattenObject.js +4 -1
  23. package/server/routes/crud/controllers/deleteCrud.js +35 -9
  24. package/server/routes/table/controllers/search.js +74 -74
  25. package/server/routes/table/controllers/tableData.js +2 -2
  26. package/server/routes/table/functions/getData.js +6 -6
  27. package/server/routes/widget/controllers/widget.del.js +89 -89
  28. package/server/routes/widget/hook/onWidgetSet.js +13 -13
  29. package/server/routes/widget/index.mjs +38 -38
package/index.js CHANGED
@@ -9,6 +9,7 @@ import proxy from '@fastify/http-proxy';
9
9
  import config from './config.js';
10
10
 
11
11
  const { maxFileSize = 512 } = config;
12
+ const { name: execName } = path.parse(process.argv0);
12
13
 
13
14
  // helpers
14
15
  // import helperPlugin from './server/helpers/index.js';
@@ -117,15 +118,35 @@ async function plugin(fastify, opt) {
117
118
  }
118
119
 
119
120
  config.proxy?.forEach?.(el => {
120
- fastify.register(proxy, {
121
- upstream: el.target,
122
- prefix: el.source,
123
- http2: false,
124
- preHandler: async (req) => {
125
- req.headers.uid = req.session?.passport?.user?.uid;
126
- Object.keys(el.headers || {})?.forEach(item => req.headers[item] = el.headers[item]);
127
- },
128
- });
121
+ if (execName === 'bun') {
122
+ fastify.all(`${el.source}/*`, async (req, reply) => {
123
+ const url = el.target.replace(/\/$/, '') + req.raw.url.replace(new RegExp(`^${el.source}`), '');
124
+ const res = await fetch(url, {
125
+ method: req.method,
126
+ headers: {
127
+ // ...req.headers,
128
+ uid: req.user?.uid,
129
+ ...(el.headers || {}),
130
+ },
131
+ body: ['PUT', 'POST'].includes(req.method) ? req.raw : undefined,
132
+ });
133
+ const resp = res.headers.get('content-type')?.includes('/json') ? await res.json() : await res.text();
134
+ reply.headers(Object.fromEntries(res.headers));
135
+ reply.status(res.status);
136
+ reply.send(resp);
137
+ });
138
+ }
139
+ else {
140
+ fastify.register(proxy, {
141
+ upstream: el.target,
142
+ prefix: el.source,
143
+ http2: false,
144
+ preHandler: async (req) => {
145
+ req.headers.uid = req.session?.passport?.user?.uid;
146
+ Object.keys(el.headers || {})?.forEach(item => req.headers[item] = el.headers[item]);
147
+ },
148
+ });
149
+ }
129
150
  });
130
151
 
131
152
  if (config.dblist) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.4.82",
3
+ "version": "1.4.84",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "keywords": [
@@ -61,4 +61,4 @@
61
61
  },
62
62
  "author": "Softpro",
63
63
  "license": "ISC"
64
- }
64
+ }
@@ -1,18 +1,18 @@
1
- import setToken from '../../plugins/crud/funcs/setToken.js';
2
-
3
- export default function tokenFunc(params) {
4
- const { data, hash } = params;
5
-
6
- if (!data?.root?.user?.uid && !hash.uid) return '-';
7
- if (!hash || typeof hash !== 'object') return '-';
8
-
9
- // const id = hash?.edit ? hash?.id : data?.root?.id;
10
- // console.log(hash)
11
- const [token] = setToken({
12
- ids: [JSON.stringify(hash)],
13
-
14
- uid: data?.root?.user?.uid || hash.uid,
15
- array: 1,
16
- });
17
- return token;
18
- }
1
+ import setToken from '../../plugins/crud/funcs/setToken.js';
2
+
3
+ export default function tokenFunc(params) {
4
+ const { data, hash } = params;
5
+
6
+ if (!data?.root?.user?.uid && !hash.uid) return '-';
7
+ if (!hash || typeof hash !== 'object') return '-';
8
+
9
+ // const id = hash?.edit ? hash?.id : data?.root?.id;
10
+ // console.log(hash)
11
+ const [token] = setToken({
12
+ ids: [JSON.stringify(hash)],
13
+
14
+ uid: data?.root?.user?.uid || hash.uid,
15
+ array: 1,
16
+ });
17
+ return token;
18
+ }
@@ -1,52 +1,52 @@
1
- import config from '../../../../config.js';
2
-
3
- import logger from '../../logger/getLogger.js';
4
- import pgClients from '../../pg/pgClients.js';
5
-
6
- import cronList from '../cronList.js';
7
- import runCron from './runCron.js';
8
- import interval2ms from './interval2ms.js';
9
-
10
- /**
11
- * interval:
12
- * - 02:54 - every day
13
- * - 2:03 - every day
14
- * - *1:43 - 2 times a day
15
- * - *12:03 - 2 times a day
16
- * - **:54 - every hour
17
- * - **:*3 - every 10 minutes
18
- * - 60 - every minute
19
- * - 10 * 60 - every 10 minutes
20
- */
21
-
22
- export default async function addCron(func, interval, pg = pgClients.client) {
23
- const { time = {}, disabled = [] } = config.cron || {};
24
-
25
- const name = func.name || func.toString().split('/').at(-1).split('\'')[0];
26
-
27
- // if (!config.isServer) return;
28
-
29
- if (disabled.includes(name)) {
30
- logger.file('cron', { name, message: 'cron disabled' });
31
- return;
32
- }
33
-
34
- cronList[name] = func;
35
-
36
- const userInterval = time[name] || interval;
37
- const [waitMs, intervalMs] = interval2ms[typeof interval](userInterval);
38
-
39
- if (intervalMs < 1000) {
40
- logger.file('cron', { name, error: `interval ${interval} too small` });
41
- return;
42
- }
43
-
44
- // setTimeout to w8 for the time to start
45
- setTimeout(() => {
46
- runCron({ pg, func, name });
47
- // interval
48
- setInterval(() => {
49
- runCron({ pg, func, name });
50
- }, intervalMs);
51
- }, waitMs);
52
- }
1
+ import config from '../../../../config.js';
2
+
3
+ import logger from '../../logger/getLogger.js';
4
+ import pgClients from '../../pg/pgClients.js';
5
+
6
+ import cronList from '../cronList.js';
7
+ import runCron from './runCron.js';
8
+ import interval2ms from './interval2ms.js';
9
+
10
+ /**
11
+ * interval:
12
+ * - 02:54 - every day
13
+ * - 2:03 - every day
14
+ * - *1:43 - 2 times a day
15
+ * - *12:03 - 2 times a day
16
+ * - **:54 - every hour
17
+ * - **:*3 - every 10 minutes
18
+ * - 60 - every minute
19
+ * - 10 * 60 - every 10 minutes
20
+ */
21
+
22
+ export default async function addCron(func, interval, pg = pgClients.client) {
23
+ const { time = {}, disabled = [] } = config.cron || {};
24
+
25
+ const name = func.name || func.toString().split('/').at(-1).split('\'')[0];
26
+
27
+ // if (!config.isServer) return;
28
+
29
+ if (disabled.includes(name)) {
30
+ logger.file('cron', { name, message: 'cron disabled' });
31
+ return;
32
+ }
33
+
34
+ cronList[name] = func;
35
+
36
+ const userInterval = time[name] || interval;
37
+ const [waitMs, intervalMs] = interval2ms[typeof interval](userInterval);
38
+
39
+ if (intervalMs < 1000) {
40
+ logger.file('cron', { name, error: `interval ${interval} too small` });
41
+ return;
42
+ }
43
+
44
+ // setTimeout to w8 for the time to start
45
+ setTimeout(() => {
46
+ runCron({ pg, func, name });
47
+ // interval
48
+ setInterval(() => {
49
+ runCron({ pg, func, name });
50
+ }, intervalMs);
51
+ }, waitMs);
52
+ }
@@ -11,7 +11,7 @@ import logger from '../../logger/getLogger.js';
11
11
  const rclient = getRedis();
12
12
 
13
13
  export default async function dataDelete({
14
- table: table1, tokenData, referer, id, pg: pg1, uid,
14
+ table: table1, tokenData, referer, id, pg: pg1, uid, query = 'true',
15
15
  }) {
16
16
  const pg = pg1 || getPG({ name: 'client' });
17
17
 
@@ -30,7 +30,7 @@ export default async function dataDelete({
30
30
 
31
31
  const { pk } = await getMeta({ pg, table });
32
32
 
33
- const delQuery = `delete from ${table} WHERE ${pk}::text = $1::text returning *`;
33
+ const delQuery = `delete from ${table} WHERE ${pk}::text = $1::text and ${query} returning *`;
34
34
 
35
35
  // for transactions
36
36
  const isClient = typeof pg.query === 'function' && typeof pg.release === 'function';
@@ -1,14 +1,14 @@
1
- import config from '../../../../config.js';
2
- import getRedis from '../../redis/funcs/getRedis.js';
3
-
4
- const rclient = getRedis({ db: 0 });
5
-
6
- export default async function getOpt(token, uid = 0) {
7
- if (!config.redis) return null;
8
-
9
- const key = `opt:${uid}:${token}`;
10
- // console.log(key);
11
- const data = await rclient.get(key);
12
- if (!data) return null;
13
- return JSON.parse(data);
14
- }
1
+ import config from '../../../../config.js';
2
+ import getRedis from '../../redis/funcs/getRedis.js';
3
+
4
+ const rclient = getRedis({ db: 0 });
5
+
6
+ export default async function getOpt(token, uid = 0) {
7
+ if (!config.redis) return null;
8
+
9
+ const key = `opt:${uid}:${token}`;
10
+ // console.log(key);
11
+ const data = await rclient.get(key);
12
+ if (!data) return null;
13
+ return JSON.parse(data);
14
+ }
@@ -1,11 +1,11 @@
1
- import path from 'node:path';
2
-
3
- import config from '../../../../../config.js';
4
-
5
- export default function getFolder(req, type = 'server') {
6
- if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
7
- const types = { local: req.root || config.root, server: req.mapServerRoot || config.mapServerRoot };
8
- const dbname = req.pg?.options?.database || req.pg?.database || config.pg?.database; // request / config params / default config params
9
- const filepath = path.posix.join(types[type] || `/data/local/${dbname || ''}`, req.folder || config.folder || '');
10
- return filepath;
11
- }
1
+ import path from 'node:path';
2
+
3
+ import config from '../../../../../config.js';
4
+
5
+ export default function getFolder(req, type = 'server') {
6
+ if (!['server', 'local'].includes(type)) throw new Error('params type is invalid');
7
+ const types = { local: req.root || config.root, server: req.mapServerRoot || config.mapServerRoot };
8
+ const dbname = req.pg?.options?.database || req.pg?.database || config.pg?.database; // request / config params / default config params
9
+ const filepath = path.posix.join(types[type] || `/data/local/${dbname || ''}`, req.folder || config.folder || '');
10
+ return filepath;
11
+ }
@@ -1,19 +1,19 @@
1
- import applyHookSync from '../hook/funcs/applyHookSync.js';
2
-
3
- function errorStatus(error) {
4
- const hook = applyHookSync('errorStatus', error);
5
- if (hook) return hook;
6
-
7
- if (error.routine === 'exec_stmt_raise' && error.file === 'pl_exec.c') {
8
- return 601;
9
- }
10
- if (error.routine === 'ExecConstraints') {
11
- return 602;
12
- }
13
- if (error.type === 'DatabaseError') {
14
- return 600;
15
- }
16
-
17
- return 500;
18
- }
19
- export default errorStatus;
1
+ import applyHookSync from '../hook/funcs/applyHookSync.js';
2
+
3
+ function errorStatus(error) {
4
+ const hook = applyHookSync('errorStatus', error);
5
+ if (hook) return hook;
6
+
7
+ if (error.routine === 'exec_stmt_raise' && error.file === 'pl_exec.c') {
8
+ return 601;
9
+ }
10
+ if (error.routine === 'ExecConstraints') {
11
+ return 602;
12
+ }
13
+ if (error.type === 'DatabaseError') {
14
+ return 600;
15
+ }
16
+
17
+ return 500;
18
+ }
19
+ export default errorStatus;
@@ -44,8 +44,8 @@ async function init(client) {
44
44
  }
45
45
 
46
46
  async function querySafe(q, param = {}) {
47
- const { args, isstream } = param;
48
- const data = await query(q, args, isstream);
47
+ const args = Array.isArray(param) ? param : (param.args || []);
48
+ const data = await query(q, args, true);
49
49
  return data;
50
50
  }
51
51
 
@@ -1,8 +1,8 @@
1
- import redisClients from './funcs/redisClients.js';
2
- import getRedis from './funcs/getRedis.js';
3
-
4
- if (!redisClients[0]) {
5
- getRedis({ db: 0 });
6
- }
7
-
8
- export default redisClients[0];
1
+ import redisClients from './funcs/redisClients.js';
2
+ import getRedis from './funcs/getRedis.js';
3
+
4
+ if (!redisClients[0]) {
5
+ getRedis({ db: 0 });
6
+ }
7
+
8
+ export default redisClients[0];
@@ -1,3 +1,3 @@
1
- const redisClients = {};
2
-
3
- export default redisClients;
1
+ const redisClients = {};
2
+
3
+ export default redisClients;
@@ -1,6 +1,11 @@
1
- /* eslint-disable no-console */
1
+ import path from 'node:path';
2
2
 
3
- import Database from 'better-sqlite3';
3
+ const { name: execName } = path.parse(process.argv0);
4
+
5
+ // import Database from 'better-sqlite3'; // error with bun
6
+ const { default: Database } = execName === 'bun'
7
+ ? { default: (await import('bun:sqlite')).Database }
8
+ : await import('better-sqlite3');
4
9
 
5
10
  import config from '../../../../config.js';
6
11
  import sqliteClients from '../sqliteClients.js';
@@ -25,7 +30,7 @@ function getSqliteAsync({
25
30
  verbose: config.trace ? console.log : undefined,
26
31
  };
27
32
 
28
- sqliteClients.client = new Database(name || ':memory:', dbConfig);
33
+ sqliteClients.client = new Database(name || ':memory:', execName === 'bun' ? undefined : dbConfig);
29
34
  init(sqliteClients.client);
30
35
 
31
36
  return sqliteClients.client;
@@ -47,7 +47,7 @@ function init(client) {
47
47
  tlist,
48
48
  });
49
49
 
50
- console.log('db connected', client.name || ':memory:');
50
+ console.log('sqlite db connected', client.name || ':memory:');
51
51
  }
52
52
 
53
53
  export default init;
@@ -1,6 +1,11 @@
1
- /* eslint-disable no-console */
1
+ import path from 'node:path';
2
2
 
3
- import Database from 'better-sqlite3';
3
+ const { name: execName } = path.parse(process.argv0);
4
+
5
+ // import Database from 'better-sqlite3';
6
+ const { default: Database } = execName === 'bun'
7
+ ? { default: (await import('bun:sqlite')).Database }
8
+ : await import('better-sqlite3');
4
9
 
5
10
  import config from '../../../config.js';
6
11
  import init from './funcs/init.js';
@@ -8,7 +13,7 @@ import init from './funcs/init.js';
8
13
  const sqliteClients = {};
9
14
 
10
15
  if (config.sqlite) {
11
- const client = new Database(config.sqlite?.name || ':memory:', {
16
+ const client = new Database(config.sqlite?.name || ':memory:', execName === 'bun' ? undefined : {
12
17
  readonly: config.sqlite?.readonly || false,
13
18
  fileMustExist: config.sqlite?.fileMustExist || false,
14
19
  timeout: config.sqlite?.statement_timeout || 10000,
@@ -1,13 +1,13 @@
1
- async function getCustomQuery({
2
- pg, table, customFilter,
3
- }) {
4
- if (!customFilter) return null;
5
- const customFilterList = customFilter?.split(',')?.map((el) => el?.split('_').pop());
6
- const { property_json: customFilterSQL } = await pg.one(`select json_agg(json_build_object('id',property_id,'name',property_key,'query',property_text)
7
- ) as property_json from admin.properties where property_key is not null and property_entity='customQuery' and object_id=$1`, [table]);
8
- const data = customFilterSQL?.length ? customFilterSQL.filter((el) => customFilterList.includes(el.id)) || [] : [];
9
- const customQuery = data?.map((el) => el.query).join(' and ');
10
- return `${customQuery}`;
11
- }
12
-
13
- export default getCustomQuery;
1
+ async function getCustomQuery({
2
+ pg, table, customFilter,
3
+ }) {
4
+ if (!customFilter) return null;
5
+ const customFilterList = customFilter?.split(',')?.map((el) => el?.split('_').pop());
6
+ const { property_json: customFilterSQL } = await pg.one(`select json_agg(json_build_object('id',property_id,'name',property_key,'query',property_text)
7
+ ) as property_json from admin.properties where property_key is not null and property_entity='customQuery' and object_id=$1`, [table]);
8
+ const data = customFilterSQL?.length ? customFilterSQL.filter((el) => customFilterList.includes(el.id)) || [] : [];
9
+ const customQuery = data?.map((el) => el.query).join(' and ');
10
+ return `${customQuery}`;
11
+ }
12
+
13
+ export default getCustomQuery;
@@ -1,34 +1,34 @@
1
- function getTable(table) {
2
- const result = table?.toLowerCase()?.replace(/[\n\r]+/g, ' ')?.split(' from ')?.filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
3
- ?.map((el) => el.split(/[ )]/)[0]);
4
- return result;
5
- }
6
-
7
- /**
8
- * @param {Number} opt.json - (1|0) 1 - Результат - Object, 0 - String
9
- * @param {String} opt.query - запит до таблиці
10
- * @param {String} opt.hash - інформація з хешу по запиту
11
- */
12
- const tableSql = {};
13
- async function getTableSql({
14
- pg, body, table, fields,
15
- }) {
16
- if (tableSql[table]) return tableSql[table];
17
-
18
- const fieldList = fields.map((el) => el.name);
19
-
20
- const tableList = body?.sql?.map((el) => getTable(el.sql)).reduce((acc, el) => acc.concat(el), []).filter((el) => fieldList.includes(pg.pk[el]));
21
-
22
- if (!tableList) { tableSql[table] = []; return []; }
23
-
24
- const data = await Promise.all(tableList?.map(async (tableEl) => {
25
- const { fields: fieldsEl } = await pg.query(`select * from ${tableEl} limit 0`);
26
- return fieldsEl.map((el) => ({ name: el.name, table: tableEl, pk: pg.pk[tableEl] }));
27
- }));
28
-
29
- tableSql[table] = data.reduce((acc, el) => acc.concat(el), []);
30
-
31
- return tableSql[table];
32
- }
33
-
34
- export default getTableSql;
1
+ function getTable(table) {
2
+ const result = table?.toLowerCase()?.replace(/[\n\r]+/g, ' ')?.split(' from ')?.filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
3
+ ?.map((el) => el.split(/[ )]/)[0]);
4
+ return result;
5
+ }
6
+
7
+ /**
8
+ * @param {Number} opt.json - (1|0) 1 - Результат - Object, 0 - String
9
+ * @param {String} opt.query - запит до таблиці
10
+ * @param {String} opt.hash - інформація з хешу по запиту
11
+ */
12
+ const tableSql = {};
13
+ async function getTableSql({
14
+ pg, body, table, fields,
15
+ }) {
16
+ if (tableSql[table]) return tableSql[table];
17
+
18
+ const fieldList = fields.map((el) => el.name);
19
+
20
+ const tableList = body?.sql?.map((el) => getTable(el.sql)).reduce((acc, el) => acc.concat(el), []).filter((el) => fieldList.includes(pg.pk[el]));
21
+
22
+ if (!tableList) { tableSql[table] = []; return []; }
23
+
24
+ const data = await Promise.all(tableList?.map(async (tableEl) => {
25
+ const { fields: fieldsEl } = await pg.query(`select * from ${tableEl} limit 0`);
26
+ return fieldsEl.map((el) => ({ name: el.name, table: tableEl, pk: pg.pk[tableEl] }));
27
+ }));
28
+
29
+ tableSql[table] = data.reduce((acc, el) => acc.concat(el), []);
30
+
31
+ return tableSql[table];
32
+ }
33
+
34
+ export default getTableSql;
@@ -1,19 +1,19 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- import config from '../../../../config.js';
5
-
6
- const loadTemplate = {};
7
-
8
- export default async function getTemplateDir(type) {
9
- if (!type) return null;
10
-
11
- const cwd = process.cwd();
12
- const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
13
-
14
- if (!loadTemplate[type]) {
15
- const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
16
- loadTemplate[type] = typeList;
17
- }
18
- return loadTemplate[type];
19
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ import config from '../../../../config.js';
5
+
6
+ const loadTemplate = {};
7
+
8
+ export default async function getTemplateDir(type) {
9
+ if (!type) return null;
10
+
11
+ const cwd = process.cwd();
12
+ const typeDir = path.join(cwd, (config.templateDir || 'server/templates'), type);
13
+
14
+ if (!loadTemplate[type]) {
15
+ const typeList = fs.existsSync(typeDir) ? fs.readdirSync(typeDir) : [];
16
+ loadTemplate[type] = typeList;
17
+ }
18
+ return loadTemplate[type];
19
+ }