@opengis/fastify-table 1.0.0

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 (50) hide show
  1. package/.eslintrc.cjs +42 -0
  2. package/README.md +26 -0
  3. package/config.js +3 -0
  4. package/crud/controllers/deleteCrud.js +10 -0
  5. package/crud/controllers/insert.js +9 -0
  6. package/crud/controllers/update.js +10 -0
  7. package/crud/funcs/dataInsert.js +23 -0
  8. package/crud/funcs/dataUpdate.js +18 -0
  9. package/crud/funcs/getOpt.js +8 -0
  10. package/crud/funcs/isFileExists.js +13 -0
  11. package/crud/funcs/setOpt.js +14 -0
  12. package/crud/index.js +29 -0
  13. package/helper.js +28 -0
  14. package/index.js +22 -0
  15. package/package.json +23 -0
  16. package/pg/funcs/autoIndex.js +89 -0
  17. package/pg/funcs/getMeta.js +31 -0
  18. package/pg/funcs/getPG.js +24 -0
  19. package/pg/funcs/init.js +41 -0
  20. package/pg/funcs/pgClients.js +2 -0
  21. package/pg/index.js +41 -0
  22. package/pg/pgClients.js +17 -0
  23. package/redis/client.js +14 -0
  24. package/redis/index.js +15 -0
  25. package/table/controllers/data.js +47 -0
  26. package/table/controllers/filter.js +17 -0
  27. package/table/controllers/form.js +10 -0
  28. package/table/controllers/suggest.js +56 -0
  29. package/table/controllers/utils/getSelect.js +20 -0
  30. package/table/controllers/utils/getSelectMeta.js +63 -0
  31. package/table/controllers/utils/getTemplate.js +24 -0
  32. package/table/funcs/getFilterSQL/index.js +75 -0
  33. package/table/funcs/getFilterSQL/util/formatValue.js +142 -0
  34. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -0
  35. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -0
  36. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -0
  37. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -0
  38. package/table/index.js +17 -0
  39. package/test/api/crud.test.js +23 -0
  40. package/test/api/table.test.js +29 -0
  41. package/test/confg.js +18 -0
  42. package/test/funcs/crud.test.js +37 -0
  43. package/test/funcs/pg.test.js +26 -0
  44. package/test/funcs/redis.test.js +19 -0
  45. package/test/funcs/table.test.js +19 -0
  46. package/test/templates/cls/test.json +10 -0
  47. package/test/templates/form/cp_building.form.json +33 -0
  48. package/test/templates/select/storage.data.json +3 -0
  49. package/test/templates/select/storage.data.sql +1 -0
  50. package/test/templates/table/gis.dataset.table.json +43 -0
package/.eslintrc.cjs ADDED
@@ -0,0 +1,42 @@
1
+ /* eslint-env node */
2
+
3
+ module.exports = {
4
+ env: {
5
+ node: true,
6
+ },
7
+ root: true,
8
+ extends: [
9
+ 'eslint:recommended',
10
+ 'airbnb-base',
11
+
12
+ ],
13
+ rules: {
14
+ 'brace-style': [2, 'stroustrup', { allowSingleLine: true }],
15
+ 'vue/max-attributes-per-line': 0,
16
+ 'vue/valid-v-for': 0,
17
+
18
+ // allow async-await
19
+ 'generator-star-spacing': 'off',
20
+
21
+ // allow paren-less arrow functions
22
+ 'arrow-parens': 0,
23
+ 'one-var': 0,
24
+ 'max-len': 0,
25
+ 'import/first': 0,
26
+ 'import/named': 2,
27
+ 'import/namespace': 2,
28
+ 'import/default': 2,
29
+ 'import/export': 2,
30
+ 'import/extensions': 0,
31
+ 'no-console': ['warn', { allow: ['warn', 'error'] }],
32
+ 'import/no-unresolved': 0,
33
+ 'import/no-extraneous-dependencies': 0,
34
+ 'linebreak-style': ['error', 'unix'],
35
+ // allow debugger during development
36
+ 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
37
+ },
38
+
39
+ parserOptions: {
40
+ ecmaVersion: 'latest',
41
+ },
42
+ };
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # fastify-table
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@opengis/fastify-table)](https://www.npmjs.com/package/@opengis/fastify-table)
4
+ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)
5
+
6
+ It standardizes the entire form building process, while taking care of everything from rendering to validation and processing:
7
+
8
+ - pg
9
+ - redis
10
+ - crud
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm i @opengis/fastify-table
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```js
21
+ fastify.register(import('@opengis/fastify-table'), config);
22
+ ```
23
+
24
+ ## Documenation
25
+
26
+ For a detailed understanding fastify-table, its features, and how to use them, refer to our [Documentation](https://apidocs.softpro.ua/gis.storage/).
package/config.js ADDED
@@ -0,0 +1,3 @@
1
+ // import pg from './pg'
2
+ const config = { allTemplates: {} };
3
+ export default config;
@@ -0,0 +1,10 @@
1
+ export default async function deleteCrud(req) {
2
+ const { funcs } = req;
3
+ const { table, id } = req.params || {};
4
+ if (!table) return { status: 404, message: 'table is required' };
5
+
6
+ const { pk } = await funcs.getMeta(table);
7
+ const data = await funcs.pg.query(`delete from ${table} where ${pk}=$1`, [id]);
8
+
9
+ return { rowCount: data.rowCount };
10
+ }
@@ -0,0 +1,9 @@
1
+ import dataInsert from '../funcs/dataInsert.js';
2
+
3
+ export default async function insert(req) {
4
+ const { table } = req.params || {};
5
+ if (!table) return { status: 404, message: 'table is required' };
6
+
7
+ const res = await dataInsert({ table, data: req.body });
8
+ return res;
9
+ }
@@ -0,0 +1,10 @@
1
+ import dataUpdate from '../funcs/dataUpdate.js';
2
+
3
+ export default async function update(req) {
4
+ const { table, id } = req.params || {};
5
+ if (!table) return { status: 404, message: 'table is required' };
6
+ if (!id) return { status: 404, message: 'id is required' };
7
+
8
+ const res = await dataUpdate({ table, id, data: req.body });
9
+ return res;
10
+ }
@@ -0,0 +1,23 @@
1
+ import pgClients from '../../pg/pgClients.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ export default async function dataInsert({ table, data, pg = pgClients.client }) {
5
+ if (!data) return null;
6
+ const { columns } = await getMeta(table);
7
+ if (!columns) return null;
8
+
9
+ const names = columns.map((el) => el.name);
10
+ const filterData = Object.keys(data)
11
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
12
+
13
+ const insertQuery = `insert into ${table}
14
+
15
+ ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
16
+
17
+ values (${filterData?.map((key, i) => `$${i + 1}`).join(',')})
18
+
19
+ returning *`;
20
+ // console.log(updateDataset);
21
+ const res = await pg.one(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' ? JSON.stringify(el[1]) : el[1]))]) || {};
22
+ return res;
23
+ }
@@ -0,0 +1,18 @@
1
+ import pgClients from '../../pg/pgClients.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ export default async function dataUpdate({
5
+ table, id, data, pg = pgClients.client,
6
+ }) {
7
+ const { columns, pk } = await getMeta(table);
8
+
9
+ const names = columns.map((el) => el.name);
10
+ const filterData = Object.keys(data)
11
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
12
+
13
+ const updateQuery = `UPDATE ${table} SET ${filterData?.map((key, i) => `"${key[0]}"=$${i + 2}`).join(',')}
14
+ WHERE ${pk} = $1 returning *`;
15
+ // console.log(updateDataset);
16
+ const res = await pg.one(updateQuery, [id, ...filterData.map((el) => (typeof el[1] === 'object' ? JSON.stringify(el[1]) : el[1]))]) || {};
17
+ return res;
18
+ }
@@ -0,0 +1,8 @@
1
+ import rclient from '../../redis/client.js';
2
+
3
+ export default async function getOpt(token) {
4
+ const key = `opt:${token}`;
5
+ const data = await rclient.get(key);
6
+ if (!data) return null;
7
+ return JSON.parse(data);
8
+ }
@@ -0,0 +1,13 @@
1
+ import { access } from 'fs/promises';
2
+
3
+ const isFileExists = async (filepath) => {
4
+ try {
5
+ await access(filepath);
6
+ return true;
7
+ }
8
+ catch (err) {
9
+ return false;
10
+ }
11
+ };
12
+
13
+ export default isFileExists;
@@ -0,0 +1,14 @@
1
+ import { createHash } from 'crypto';
2
+ import rclient from '../../redis/client.js';
3
+
4
+ function md5(string) {
5
+ return createHash('md5').update(string).digest('hex');
6
+ }
7
+
8
+ export default async function setOpt(params) {
9
+ const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params), 'hex').toString('base64').replace(/[+-=]+/g, '');
10
+ // const token = md5(params);
11
+ const key = `opt:${token}`;
12
+ await rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
13
+ return token;
14
+ }
package/crud/index.js ADDED
@@ -0,0 +1,29 @@
1
+ import fp from 'fastify-plugin';
2
+
3
+ import getOPt from './funcs/getOpt.js';
4
+ import setOpt from './funcs/setOpt.js';
5
+ import isFileExists from './funcs/isFileExists.js';
6
+ import dataUpdate from './funcs/dataUpdate.js';
7
+
8
+ import update from './controllers/update.js';
9
+ import insert from './controllers/insert.js';
10
+ import deleteCrud from './controllers/deleteCrud.js';
11
+
12
+ import config from '../config.js';
13
+
14
+ const prefix = config.prefix || '/api';
15
+
16
+ async function plugin(fastify) {
17
+ // funcs
18
+ fastify.decorate('setOpt', setOpt);
19
+ fastify.decorate('getOpt', getOPt);
20
+ fastify.decorate('dataUpdate', dataUpdate);
21
+ fastify.decorate('isFileExists', isFileExists);
22
+
23
+ // api
24
+ fastify.put(`${prefix}/crud/:table/:id`, {}, update);
25
+ fastify.delete(`${prefix}/crud/:table/:id`, {}, deleteCrud);
26
+ fastify.post(`${prefix}/crud/:table`, {}, insert);
27
+ }
28
+
29
+ export default plugin;
package/helper.js ADDED
@@ -0,0 +1,28 @@
1
+ // This file contains code that we reuse
2
+ // between our tests.
3
+ import Fastify from 'fastify';
4
+ import config from './test/confg.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 ADDED
@@ -0,0 +1,22 @@
1
+ // import pg from 'pg';
2
+ import fp from 'fastify-plugin';
3
+ import config from './config.js';
4
+ // import rclient from './redis/client.js';
5
+
6
+ import redisPlugin from './redis/index.js';
7
+ import pgPlugin from './pg/index.js';
8
+ import tablePlugin from './table/index.js';
9
+ import crudPlugin from './crud/index.js';
10
+
11
+ async function plugin(fastify, opt) {
12
+ // console.log(opt);
13
+ config.pg = opt.pg;
14
+ config.redis = opt.redis;
15
+
16
+ redisPlugin(fastify);
17
+ await pgPlugin(fastify, opt);
18
+ tablePlugin(fastify, opt);
19
+ crudPlugin(fastify, opt);
20
+ }
21
+ export default fp(plugin);
22
+ // export { rclient };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@opengis/fastify-table",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "core-plugins",
6
+ "main": "index.js",
7
+ "scripts": {
8
+ "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
9
+ "test": "echo \"Error: no test specified\" && exit 1"
10
+ },
11
+ "dependencies": {
12
+ "ioredis": "^5.3.2",
13
+ "fastify": "^4.26.1",
14
+ "fastify-plugin": "^4.0.0",
15
+ "pg": "^8.11.3"
16
+ },
17
+ "devDependencies": {
18
+ "eslint": "^8.49.0",
19
+ "eslint-config-airbnb": "^19.0.4"
20
+ },
21
+ "author": "Softpro",
22
+ "license": "ISC"
23
+ }
@@ -0,0 +1,89 @@
1
+ // const rclient = require('../../redis/client')
2
+ import pgClient from '../pgClients.js';
3
+
4
+ // subfunc
5
+ const getTable = ({ table }) => table.toLowerCase().replace(/[\n\r]+/g, ' ').split(' from ')
6
+ .filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
7
+ .map((el) => el.split(/[ )]/)[0]);
8
+
9
+ const loadedIndex = {};
10
+
11
+ // main func
12
+ async function autoIndex({ table, columns: filter, pg = pgClient.client }) {
13
+ if (!filter?.length || !table) return null;
14
+
15
+ const attrs = filter.map((el) => (el.name || el).replace(/'/g, '')).sort();
16
+ const types = filter.map((el) => (el.name ? el : { name: el }))
17
+ .reduce((p, el) => ({ ...p, [el.name]: el.type || '-' }), {});
18
+
19
+ const redisKey = `autoindex1:${table}:${attrs.join(';')}`;
20
+ const tableList = getTable({ table });
21
+ const existsCache = loadedIndex[redisKey];
22
+ if (existsCache) { return 'ok'; }
23
+
24
+ const tbs = tableList[0];
25
+ const [ns, tbl] = tableList[0].split('.');
26
+ const { rows: index } = await pg.query(`select * from pg_indexes where tablename = '${tbl}' and schemaname = '${ns}'`);
27
+
28
+ if (existsCache && index?.length > 0) { return null; }
29
+ // console.log('autoindex', table, filter?.map((el) => el.name || el));
30
+ const { rows: cols } = await pg.query(`SELECT attrelid::regclass AS tbl, attname AS aname, atttypid::regtype AS datatype, atttypid
31
+ FROM pg_attribute WHERE attrelid = '${tbs}'::regclass and attname = any('{ ${attrs} }')`);
32
+
33
+ const qIndex = [];
34
+ const indexAr = {};
35
+
36
+ // console.log(cols);
37
+ for (let i = 0; i < cols.length; i += 1) {
38
+ const el = cols[i];
39
+ el.relname = tbl;
40
+ el.nspname = ns;
41
+
42
+ const indexUsing = (el.datatype === 'geometry' ? 'gist' : null)
43
+ || (types[el.aname] === 'Text' || el.datatype?.includes('[]') ? 'gin' : null)
44
+ || 'btree';
45
+
46
+ const name = `${el.nspname}_${el.relname}_${el.aname}_${indexUsing}_idx`;
47
+ const exists = index.filter((ind) => ind.tablename === el.relname && ind.schemaname === el.nspname && ind.indexdef.includes(types[el.aname] === 'Text'
48
+ ? `gin (${el.aname} gin_trgm_ops)` : `btree (${el.aname})`));
49
+
50
+ indexAr[el.aname] = {
51
+ name, type: el.datatype, exists, // exists1,
52
+ };
53
+
54
+ // drop
55
+ if (exists?.length > 1) {
56
+ exists.filter((ind, i1) => i1).forEach((ind) => qIndex.push(`DROP INDEX if exists ${ind.schemaname}.${ind.indexname} `));
57
+ }
58
+
59
+ // add
60
+ if (exists?.length === 0) {
61
+ // console.log(`${name} - ${el.datatype}`);
62
+
63
+ const suffix = types[el.aname] === 'Text' ? 'gin_trgm_ops' : '';
64
+ if (['text'].includes(el?.datatype)) {
65
+ qIndex.push(`CREATE INDEX if not exists ${name} ON ${el.nspname}.${el.relname} USING ${indexUsing} (${el.aname} ${suffix})`);
66
+ }
67
+ if (indexUsing === 'gist') {
68
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'gist1')}
69
+ ON ${el.nspname}.${el.relname} USING gist (${el.aname})`);
70
+
71
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'area')}
72
+ ON ${el.nspname}.${el.relname} USING btree (st_area(st_transform(${el.aname},3857)))`);
73
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', '4326')}
74
+ ON ${el.nspname}.${el.relname} USING gist (st_transform(${el.aname},4326))`);
75
+ }
76
+ }
77
+ }
78
+
79
+ loadedIndex[redisKey] = 1;
80
+ // throw qIndex;
81
+ if (!qIndex.length) return null;
82
+
83
+ // console.log(qIndex.filter((v, i, a) => a.indexOf(v) === i));
84
+ // logger.file('index', { table, filter, sql: qIndex.filter((v, i, a) => a.indexOf(v) === i) });
85
+ qIndex.filter((v, i, a) => a.indexOf(v) === i).map((el) => pg.one(el).catch((err) => console.log(err.toString())));
86
+ return 'ok';
87
+ }
88
+
89
+ export default autoIndex;
@@ -0,0 +1,31 @@
1
+ import pgClient from '../pgClients.js';
2
+
3
+ const data = {};
4
+
5
+ // decorator
6
+ export default async function getMeta(opt) {
7
+ const pg = pgClient.client;
8
+ const table = opt.table || opt;
9
+
10
+ if (data[table]) return data[table];
11
+
12
+ if (!pg.tlist.includes(table)) {
13
+ return { error: `${table} - not found`, status: 400 };
14
+ }
15
+
16
+ const { fields } = await pg.query(`select * from ${table} where $1=$1 limit 0`, [1]);
17
+ const { pks1 } = await pg.one(`SELECT json_object_agg(c.conrelid::regclass, a.attname) as pks1 FROM pg_constraint c
18
+ left join pg_attribute a on c.conrelid=a.attrelid and a.attnum = c.conkey[1] WHERE c.contype='p'::"char"`, { cache: 0 });
19
+ const pk = pks1[table];
20
+
21
+ const geomAttr = fields.find((el) => pg.pgType[el.dataTypeID] === 'geometry')?.name; // change geometry text to geometry code
22
+ const q = `select st_extent( ${geomAttr}) as bounds, count(*),
23
+ (select st_srid(${geomAttr}) from ${table} where ${geomAttr} is not null limit 1) as srid,
24
+ json_agg(distinct ST_GeometryType(${geomAttr}))::json as geometry from ${table}
25
+ where ${geomAttr} is not null `;
26
+ const geom = await pg.one(q, { cache: 0 });
27
+
28
+ const res = { pk, columns: fields, geom };
29
+ data[table] = res;
30
+ return res;
31
+ }
@@ -0,0 +1,24 @@
1
+ import pg from 'pg';
2
+ import config from '../../config.js';
3
+ import pgClients from '../pgClients.js';
4
+ import init from './init.js';
5
+
6
+ async function getPG({
7
+ user, password, host, port, db,
8
+ }) {
9
+ if (pgClients[db]) return pgClients[db];
10
+
11
+ const dbConfig = {
12
+ user: user || config.pg?.user,
13
+ password: password || config.pg?.password,
14
+ host: host || config.pg?.host,
15
+ port: port || config.pg?.port,
16
+ database: db || config.pg?.db,
17
+ };
18
+
19
+ pgClients[db] = new pg.Pool(dbConfig);
20
+ init(pgClients[db]);
21
+ return pgClients[db];
22
+ }
23
+
24
+ export default getPG;
@@ -0,0 +1,41 @@
1
+ import crypto from 'crypto';
2
+
3
+ // import pg from 'pg';
4
+ import rclient from '../../redis/client.js';
5
+ // import config from '../config.js';
6
+
7
+ async function init(client) {
8
+ const textQuery = `select
9
+ (select json_object_agg(conrelid::regclass ,(SELECT attname FROM pg_attribute WHERE attrelid = c.conrelid and attnum = c.conkey[1]))
10
+ from pg_constraint c where contype='p' and connamespace::regnamespace::text not in ('sde')) as pk,
11
+ (SELECT json_object_agg(t.oid::text,pg_catalog.format_type(t.oid, NULL)) FROM pg_catalog.pg_type t) as "pgType"`;
12
+ const { pgType, pk } = await client.query(textQuery).then((d) => d.rows[0]);
13
+
14
+ const tlist = await client.query(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist
15
+ from pg_class where relkind in ('r','v')`).then((d) => d.rows[0].tlist);
16
+
17
+ async function one(query, param = {}) {
18
+ const data = await client.query(query, Array.isArray(param) ? param : param.args || []);
19
+ const result = ((Array.isArray(data) ? data.pop() : data)?.rows || [])[0] || {};
20
+ return result;
21
+ }
22
+
23
+ async function queryCache(query) {
24
+ const hash = crypto.createHash('sha1').update(query).digest('base64');
25
+ const keyCache = `pg:${hash}`;
26
+ const cache = await rclient.get(keyCache);
27
+ if (cache) {
28
+ return JSON.parse(cache);
29
+ }
30
+ const data = await client.query(query);
31
+ rclient.set(keyCache, JSON.stringify(data), 'EX', 60 * 60);
32
+ return data;
33
+ }
34
+
35
+ Object.assign(client, {
36
+ one, pgType, pk, tlist, queryCache,
37
+ });
38
+ }
39
+
40
+ // export default client;
41
+ export default init;
@@ -0,0 +1,2 @@
1
+ const pgClients = {};
2
+ export default pgClients;
package/pg/index.js ADDED
@@ -0,0 +1,41 @@
1
+ // import fp from 'fastify-plugin';
2
+ import pg from 'pg';
3
+ import pgClients from './funcs/pgClients.js';
4
+ import init from './funcs/init.js';
5
+ import autoIndex from './funcs/autoIndex.js';
6
+ import getMeta from './funcs/getMeta.js';
7
+ import getPG from './funcs/getPG.js';
8
+
9
+ function close() {
10
+ // console.log('pg close');
11
+ Object.keys(pgClients).forEach((el) => {
12
+ // console.log(el);
13
+ pgClients[el].end();
14
+ });
15
+
16
+ // return pgClients.client.end();
17
+ }
18
+
19
+ async function plugin(fastify, config) {
20
+ const client = new pg.Pool({
21
+ host: config.pg?.host || '127.0.0.1',
22
+ port: config.pg?.port || 5432,
23
+ database: config.pg?.database || 'postgres',
24
+ user: config.pg?.user || 'postgres',
25
+ password: config.pg?.password || 'postgres',
26
+ });
27
+ await init(client);
28
+ fastify.addHook('onRequest', async (req) => {
29
+ // req.funcs = fastify;
30
+ req.pg = client;
31
+ });
32
+ pgClients.client = client;
33
+
34
+ // fastify.decorate('pg', client);
35
+ fastify.decorate('autoIndex', autoIndex);
36
+ fastify.decorate('getMeta', getMeta);
37
+ fastify.decorate('getPG', getPG);
38
+ fastify.addHook('onClose', close);
39
+ }
40
+
41
+ export default plugin;
@@ -0,0 +1,17 @@
1
+ import pg from 'pg';
2
+ import config from '../config.js';
3
+ import init from './funcs/init.js';
4
+
5
+ const pgClients = {};
6
+ if (config.pg) {
7
+ const client = new pg.Pool({
8
+ host: config.pg?.host || '127.0.0.1',
9
+ port: config.pg?.port || 5432,
10
+ database: config.pg?.database || 'postgres',
11
+ user: config.pg?.user || 'postgres',
12
+ password: config.pg?.password || 'postgres',
13
+ });
14
+ await init(client);
15
+ pgClients.client = client;
16
+ }
17
+ export default pgClients;
@@ -0,0 +1,14 @@
1
+ import Redis from 'ioredis';
2
+
3
+ // const config = {};
4
+ import config from '../config.js';
5
+
6
+ const rclient = new Redis({
7
+ keyPrefix: `${config?.db}:`,
8
+ host: config?.redis?.host || '127.0.0.1',
9
+ port: config?.redis?.port || 6379, // Redis port
10
+ family: 4, // 4 (IPv4) or 6 (IPv6)
11
+ closeClient: true,
12
+ });
13
+
14
+ export default rclient;
package/redis/index.js ADDED
@@ -0,0 +1,15 @@
1
+ import client from './client.js';
2
+
3
+ function close(fastify) {
4
+ fastify.rclient.quit();
5
+ // fastify.rclient2.quit();
6
+ }
7
+
8
+ async function plugin(fastify) {
9
+ client.getJSON = client.get;
10
+ fastify.decorate('rclient', client);
11
+ // fastify.decorate('rclient2', client2);
12
+ fastify.addHook('onClose', close);
13
+ }
14
+
15
+ export default plugin;
@@ -0,0 +1,47 @@
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getFilterSQL from '../funcs/getFilterSQL/index.js';
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+
5
+ const maxLimit = 10;
6
+ export default async function data(req) {
7
+ const time = Date.now();
8
+ const {
9
+ pg, params, query = {},
10
+ } = req;
11
+
12
+ const loadTable = await getTemplate('table', params.table);
13
+
14
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
15
+
16
+ const {
17
+ table, columns, sql, filters, form, meta,
18
+ } = loadTable;
19
+ const { pk } = await getMeta(table);
20
+
21
+ const cols = columns.map((el) => el.name || el).join(',');
22
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
23
+
24
+ const fData = query.filter ? await getFilterSQL(query.filter, {
25
+ table,
26
+ json: 1,
27
+ }) : {};
28
+
29
+ const keyQuery = query.key && loadTable.key && !params.id ? `${loadTable.key}=$1` : null;
30
+
31
+ const limit = Math.min(maxLimit, +(query.limit || 10));
32
+
33
+ const offset = query.page ? ` offset ${(query.page - 1) * limit}` : '';
34
+ // id, query, filter
35
+ const where = [(params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q].filter((el) => el);
36
+ const q = `select ${pk ? `"${pk}" as id,` : ''} ${query.id || query.key ? '*' : cols || '*'} from ${table} t ${sqlTable} where ${where.join(' and ') || 'true'} ${offset} limit ${limit}`;
37
+
38
+ if (query.sql) { return q; }
39
+
40
+ const { rows } = await pg.query(q, (params.id ? [params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
41
+
42
+ const total = keyQuery || params.id ? rows.length : await pg.queryCache(`select count(*) from ${table} where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
43
+
44
+ return {
45
+ time: Date.now() - time, total, pk, form, rows, meta, columns, filters,
46
+ };
47
+ }
@@ -0,0 +1,17 @@
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getSelect from './utils/getSelect.js';
3
+
4
+ export default async function filter(req) {
5
+ const time = Date.now();
6
+ const {
7
+ params,
8
+ } = req;
9
+ const loadTable = await getTemplate('table', params.table);
10
+ if (!loadTable) { return { status: 404, message: 'not found' }; }
11
+
12
+ await Promise.all(loadTable?.filters.filter((el) => el.data).map(async (el) => {
13
+ const cls = await getSelect(el.data);
14
+ Object.assign(el, { options: cls?.arr });
15
+ }));
16
+ return { time: Date.now() - time, filters: loadTable?.filters || [] };
17
+ }
@@ -0,0 +1,10 @@
1
+ import getTemplate from './utils/getTemplate.js';
2
+
3
+ export default async function formFunction(req) {
4
+ const time = Date.now();
5
+ const { params } = req;
6
+ const form = await getTemplate('form', params.form);
7
+ if (!form) { return { status: 404, message: 'not found' }; }
8
+
9
+ return { time: Date.now() - time, form };
10
+ }