@opengis/fastify-table 1.0.83 → 1.0.85

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/Changelog.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # fastify-table
2
2
 
3
+ ## 1.0.85 - 23.08.2024
4
+
5
+ - data API meta cls support
6
+
7
+ ## 1.0.84 - 22.08.2024
8
+
9
+ - suggest table:column support
10
+
3
11
  ## 1.0.83 - 20.08.2024
4
12
 
5
13
  - code optimization
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.0.83",
3
+ "version": "1.0.85",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "main": "index.js",
@@ -12,6 +12,10 @@
12
12
  "table": "gis.dataset",
13
13
  "order": "dataset_name",
14
14
  "meta": {
15
+ "cls": {
16
+ "dataset_id": "test.storage.data"
17
+ },
18
+ "bbox": "geom",
15
19
  "title": "dataset_name",
16
20
  "search": "dataset_name,dataset_id"
17
21
  },
@@ -1,97 +1,102 @@
1
- import getTemplate from './utils/getTemplate.js';
2
- import getFilterSQL from '../funcs/getFilterSQL/index.js';
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
- import metaFormat from '../funcs/metaFormat/index.js';
5
- import getAccess from '../../crud/funcs/getAccess.js';
6
- import setToken from '../../crud/funcs/setToken.js';
7
- import gisIRColumn from './utils/gisIRColumn.js';
8
-
9
- const maxLimit = 100;
10
- export default async function dataAPI({
11
- pg, params, funcs = {}, query = {}, opt = {}, uid: uid1, req, session,
12
- }) {
13
- const time = Date.now();
14
-
15
- const uid = session?.passport?.user?.uid || uid1 || query.uid || 0;
16
-
17
- const loadTable = await getTemplate('table', params.table);
18
-
19
- if (!loadTable) { return { message: 'template not found', status: 404 }; }
20
-
21
- const {
22
- table, columns, sql, cardSql, filters, form, meta, sqlColumns, ispublic,
23
- } = loadTable;
24
- const { pk, columns: dbColumns = [] } = await getMeta(table);
25
-
26
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
27
-
28
- const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
29
- const columnList = dbColumns.map((el) => el.name || el).join(',');
30
- const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
31
- const cardSqlFiltered = opt?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
32
- const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (select json_agg(row_to_json(q)) as ${el.name} from (${el.sql})q) ct${i} on 1=1 `).join('') || '' : '';
33
-
34
- if (params.id && columnList.includes(params.id)) {
35
- return gisIRColumn({
36
- pg, funcs, layer: params.table, column: params.id, sql: query.sql,
37
- });
38
- }
39
-
40
- const fData = query.filter || query.search ? await getFilterSQL({
41
- filter: query.filter,
42
- search: query.search,
43
- table: params.table,
44
- json: 1,
45
- }) : {};
46
-
47
- const keyQuery = query.key && loadTable.key && !(opt?.id || params.id) ? `${loadTable.key}=$1` : null;
48
-
49
- const limit = Math.min(maxLimit, +(query.limit || 20));
50
-
51
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
52
- // id, query, filter
53
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
54
-
55
- const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
56
- const state = loadTable.filterState && query.state ? loadTable.filterState[query.state]?.sql : null;
57
- const custom = loadTable.filterCustom && query.custom ? loadTable.filterCustom[query.custom]?.sql : null;
58
- const search = loadTable.meta?.search && query.search ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search}%'`).join(' or ')})` : null;
59
-
60
- const access = await getAccess(req, params.table);
61
- const where = [(opt?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, state, custom, search, access?.query || '1=1'].filter((el) => el);
62
- const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
63
- const q = `select ${pk ? `"${pk}" as id,` : ''} ${columnList.includes('geom') ? 'st_asgeojson(geom)::json as geom,' : ''} ${query.id || query.key ? '*' : sqlColumns || cols || '*'} ${cardColumns} from ${table} t ${sqlTable} ${cardSqlTable} where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
64
-
65
- if (query.sql === '1') { return q; }
66
-
67
- const { rows } = await pg.query(q, (opt?.id || params.id ? [opt?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
68
-
69
- const total = keyQuery || opt?.id || params.id ? rows.length : await pg.queryCache(`select count(*) from ${table} t ${sqlTable} where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
70
-
71
- await metaFormat({ rows, table: params.table });
72
- const res = {
73
- time: Date.now() - time, card: loadTable.card, actions: loadTable.actions, access, total, count: rows.length, pk, form, rows, meta, columns, filters,
74
- };
75
-
76
- if (!funcs.config?.security?.disableToken) {
77
- const addTokens = setToken({
78
- ids: [JSON.stringify({ add: loadTable.table, form: loadTable.form })],
79
- mode: 'a',
80
- uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
81
- array: 1,
82
- });
83
- Object.assign(res, { addToken: addTokens[0] });
84
-
85
- rows.forEach((row) => {
86
- const editTokens = setToken({
87
- ids: [JSON.stringify({ id: row.id, table: loadTable.table, form: loadTable.form })],
88
- mode: 'w',
89
- uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
90
- array: 1,
91
- });
92
- Object.assign(row, { token: editTokens[0] });
93
- });
94
- }
95
-
96
- return res;
97
- }
1
+ import getTemplate from './utils/getTemplate.js';
2
+ import getFilterSQL from '../funcs/getFilterSQL/index.js';
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+ import metaFormat from '../funcs/metaFormat/index.js';
5
+ import getAccess from '../../crud/funcs/getAccess.js';
6
+ import setToken from '../../crud/funcs/setToken.js';
7
+ import gisIRColumn from './utils/gisIRColumn.js';
8
+
9
+ const maxLimit = 100;
10
+ export default async function dataAPI({
11
+ pg, params, funcs = {}, query = {}, opt = {}, uid: uid1, req, session,
12
+ }) {
13
+ const time = Date.now();
14
+
15
+ const uid = session?.passport?.user?.uid || uid1 || query.uid || 0;
16
+
17
+ const loadTable = await getTemplate('table', params.table);
18
+
19
+ if (!loadTable) { return { message: 'template not found', status: 404 }; }
20
+
21
+ const {
22
+ table, columns, sql, cardSql, filters, form, meta, sqlColumns, ispublic,
23
+ } = loadTable;
24
+ const { pk, columns: dbColumns = [] } = await getMeta(table);
25
+
26
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
27
+
28
+ const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
29
+ const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
30
+ ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
31
+ : '';
32
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
33
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
34
+ const cardSqlFiltered = opt?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
35
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (select json_agg(row_to_json(q)) as ${el.name} from (${el.sql})q) ct${i} on 1=1 `).join('') || '' : '';
36
+
37
+ if (params.id && columnList.includes(params.id)) {
38
+ return gisIRColumn({
39
+ pg, funcs, layer: params.table, column: params.id, sql: query.sql,
40
+ });
41
+ }
42
+
43
+ const fData = query.filter || query.search ? await getFilterSQL({
44
+ filter: query.filter,
45
+ search: query.search,
46
+ table: params.table,
47
+ json: 1,
48
+ }) : {};
49
+
50
+ const keyQuery = query.key && loadTable.key && !(opt?.id || params.id) ? `${loadTable.key}=$1` : null;
51
+
52
+ const limit = Math.min(maxLimit, +(query.limit || 20));
53
+
54
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
55
+ // id, query, filter
56
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
57
+
58
+ const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
59
+ const state = loadTable.filterState && query.state ? loadTable.filterState[query.state]?.sql : null;
60
+ const custom = loadTable.filterCustom && query.custom ? loadTable.filterCustom[query.custom]?.sql : null;
61
+ const search = loadTable.meta?.search && query.search ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search}%'`).join(' or ')})` : null;
62
+ const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
63
+ const bbox = meta?.bbox && queryBbox.filter((el) => !Number.isNaN(el))?.length === 4 ? `${meta.bbox} && 'box(${queryBbox[0]} ${queryBbox[1]},${queryBbox[2]} ${queryBbox[3]})'::box2d ` : undefined;
64
+
65
+ const access = await getAccess(req, params.table);
66
+ const where = [(opt?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, state, custom, search, access?.query || '1=1', bbox].filter((el) => el);
67
+ const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
68
+ const q = `select ${pk ? `"${pk}" as id,` : ''} ${columnList.includes('geom') ? 'st_asgeojson(geom)::json as geom,' : ''} ${query.id || query.key ? '*' : sqlColumns || cols || '*'} ${metaCols} ${cardColumns} from ${table} t ${sqlTable} ${cardSqlTable} where ${where.join(' and ') || 'true'} ${order} ${offset} limit ${limit}`;
69
+
70
+ if (query.sql === '1') { return q; }
71
+
72
+ const { rows } = await pg.query(q, (opt?.id || params.id ? [opt?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
73
+
74
+ const total = keyQuery || opt?.id || params.id ? rows.length : await pg.queryCache(`select count(*) from ${table} t ${sqlTable} where ${where.join(' and ') || 'true'}`).then((el) => el?.rows[0]?.count);
75
+
76
+ await metaFormat({ rows, table: params.table });
77
+ const res = {
78
+ time: Date.now() - time, card: loadTable.card, actions: loadTable.actions, access, total, count: rows.length, pk, form, rows, meta, columns, filters,
79
+ };
80
+
81
+ if (!funcs.config?.security?.disableToken) {
82
+ const addTokens = setToken({
83
+ ids: [JSON.stringify({ add: loadTable.table, form: loadTable.form })],
84
+ mode: 'a',
85
+ uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
86
+ array: 1,
87
+ });
88
+ Object.assign(res, { addToken: addTokens[0] });
89
+
90
+ rows.forEach((row) => {
91
+ const editTokens = setToken({
92
+ ids: [JSON.stringify({ id: row.id, table: loadTable.table, form: loadTable.form })],
93
+ mode: 'w',
94
+ uid: funcs.config?.auth?.disable || ispublic ? '1' : uid,
95
+ array: 1,
96
+ });
97
+ Object.assign(row, { token: editTokens[0] });
98
+ });
99
+ }
100
+
101
+ return res;
102
+ }
@@ -1,62 +1,79 @@
1
- import getSelectMeta from './utils/getSelectMeta.js';
2
- import getPG from '../../pg/funcs/getPG.js';
3
- import config from '../../config.js';
4
-
5
- const limit = 50;
6
- const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Cache-Control': 'no-cache' };
7
-
8
- export default async function suggest(req) {
9
- const { params, query, pg: pg1 } = req;
10
-
11
- const lang = query.lang || 'ua';
12
- const time = Date.now();
13
- const parent = query.parent || '';
14
-
15
- const selectName = query.sel || query.name || params.data;
16
- if (!selectName) return { headers, status: 400, message: 'name is required' };
17
-
18
- const meta = await getSelectMeta({ name: selectName });
19
- const pg = meta?.db ? getPG(meta.db) : pg1;
20
- if (!meta) return { headers, status: 404, message: 'Not found query select ' };
21
- if (query.meta) return meta;
22
-
23
- const { arr, searchQuery } = meta;
24
-
25
- if (arr) {
26
- const lower = query.key?.toLowerCase();
27
- const data = query.key || query.val
28
- ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
29
- : arr;
30
- return {
31
- limit, count: data.length, mode: 'array', time: Date.now() - time, data,
32
- };
33
- }
34
-
35
- // search
36
- const search = query.key ? searchQuery : null;
37
-
38
- // val
39
- // const pk = meta.originalCols.split(',')[0];
40
- const val = query.val ? ` id=any('{${query.val.replace(/'/g, "''")}}')` : '';
41
-
42
- const sqlSuggest = `${meta.original.replace(/{{parent}}/gi, parent)} where ${[search, val, 'id is not null'].filter((el) => el).join(' and ') || 'true'} limit ${limit}`;
43
- if (query.sql) return sqlSuggest;
44
-
45
- // query
46
- const { rows: dataNew } = meta.searchColumn ? { rows: [] } : await pg.query(sqlSuggest, query.key ? [`${query.key}%`] : []);
47
- const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`%${query.key}%`] : []) : {};
48
- const ids = dataNew.map((el) => el.id);
49
- const data = dataNew.concat((dataNew1 || []).filter((el) => !ids?.includes(el.id)));
50
-
51
- const message = {
52
- time: Date.now() - time,
53
- count: data.length,
54
- total: meta.count - 0,
55
- mode: 'sql',
56
- db: meta.db,
57
- sql: config.local ? sqlSuggest : undefined,
58
- data,
59
- };
60
-
61
- return message;
62
- }
1
+ import getSelectMeta from './utils/getSelectMeta.js';
2
+ import getPG from '../../pg/funcs/getPG.js';
3
+ import config from '../../config.js';
4
+ import getTemplate from './utils/getTemplate.js';
5
+ import getTableSql from '../funcs/getFilterSQL/util/getTableSql.js';
6
+
7
+ const limit = 50;
8
+ const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Cache-Control': 'no-cache' };
9
+
10
+ export default async function suggest(req) {
11
+ const { params, query, pg: pg1 } = req;
12
+
13
+ const lang = query.lang || 'ua';
14
+ const time = Date.now();
15
+ const parent = query.parent || '';
16
+
17
+ const [table, column] = params.data?.includes(':') ? params.data.split(':') : [];
18
+ const selectName = query.sel || query.name || params.data;
19
+ if (!selectName) return { headers, status: 400, message: 'name is required' };
20
+
21
+ const body = await getTemplate('table', table);
22
+ if (table && !pg1.pk[body?.table || table]) {
23
+ return { headers, status: 400, message: 'param name is invalid: 1' };
24
+ }
25
+ const columnExists = true;
26
+ if (table && (!column || !columnExists)) {
27
+ return { headers, status: 400, message: 'param name is invalid: 2' };
28
+ }
29
+
30
+ const meta = table && column
31
+ ? {
32
+ original: `with c(id,text) as (select row_number() over(), ${column} from ${body?.table || table} group by ${column} ) select * from c`,
33
+ searchQuery: '("text" ilike $1 )',
34
+ }
35
+ : await getSelectMeta({ name: selectName });
36
+ const pg = meta?.db ? getPG(meta.db) : pg1;
37
+ if (!meta) return { headers, status: 404, message: 'Not found query select ' };
38
+ if (query.meta) return meta;
39
+
40
+ const { arr, searchQuery } = meta;
41
+
42
+ if (arr) {
43
+ const lower = query.key?.toLowerCase();
44
+ const data = query.key || query.val
45
+ ? arr?.filter((el) => !lower || (el[lang] || el.text)?.toLowerCase()?.indexOf(lower) !== -1)?.filter((el) => !query.val || el.id === query.val)
46
+ : arr;
47
+ return {
48
+ limit, count: data.length, mode: 'array', time: Date.now() - time, data,
49
+ };
50
+ }
51
+
52
+ // search
53
+ const search = query.key ? searchQuery : null;
54
+
55
+ // val
56
+ // const pk = meta.originalCols.split(',')[0];
57
+ const val = query.val ? ` id=any('{${query.val.replace(/'/g, "''")}}')` : '';
58
+
59
+ const sqlSuggest = `${meta.original.replace(/{{parent}}/gi, parent)} where ${[search, val, 'id is not null'].filter((el) => el).join(' and ') || 'true'} limit ${limit}`;
60
+ if (query.sql) return sqlSuggest;
61
+
62
+ // query
63
+ const { rows: dataNew } = meta.searchColumn ? { rows: [] } : await pg.query(sqlSuggest, query.key ? [`${query.key}%`] : []);
64
+ const { rows: dataNew1 } = dataNew.length < limit ? await pg.query(sqlSuggest, query.key ? [`%${query.key}%`] : []) : {};
65
+ const ids = dataNew.map((el) => el.id);
66
+ const data = dataNew.concat((dataNew1 || []).filter((el) => !ids?.includes(el.id)));
67
+
68
+ const message = {
69
+ time: Date.now() - time,
70
+ count: data.length,
71
+ total: meta.count - 0,
72
+ mode: 'sql',
73
+ db: meta.db,
74
+ sql: config.local ? sqlSuggest : undefined,
75
+ data,
76
+ };
77
+
78
+ return message;
79
+ }
@@ -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,27 +1,28 @@
1
- import getTemplate from '../../controllers/utils/getTemplate.js';
2
- import getSelectVal from './getSelectVal.js';
3
-
4
- export default async function metaFormat({ rows, table }) {
5
- const loadTable = await getTemplate('table', table);
6
- const selectCols = loadTable?.columns?.filter((e) => e.data);
7
- if (!selectCols?.length) return rows;
8
-
9
- // cls & select format
10
-
11
- await Promise.all(selectCols?.map(async (attr) => {
12
- const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
13
- if (!values.length) return null;
14
-
15
- const cls = await getSelectVal({ name: attr.data, values });
16
- if (!cls) return null;
17
- rows.forEach(el => {
18
- const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
19
- if (!val) return;
20
- Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
21
- });
22
-
23
- return null;
24
- }));
25
-
26
- return rows;
27
- }
1
+ import getTemplate from '../../controllers/utils/getTemplate.js';
2
+ import getSelectVal from './getSelectVal.js';
3
+
4
+ export default async function metaFormat({ rows, table }) {
5
+ const loadTable = await getTemplate('table', table);
6
+ const selectCols = loadTable?.columns?.filter((e) => e.data);
7
+ const metaCls = Object.keys(loadTable?.meta?.cls || {}).map((el) => ({ name: el, data: loadTable?.meta?.cls[el] }));
8
+ if (!selectCols?.length && !metaCls?.length) return rows;
9
+
10
+ // cls & select format
11
+
12
+ await Promise.all(selectCols.concat(metaCls)?.map(async (attr) => {
13
+ const values = [...new Set(rows?.map((el) => el[attr.name]).flat())].filter((el) => el);
14
+ if (!values.length) return null;
15
+
16
+ const cls = await getSelectVal({ name: attr.data, values });
17
+ if (!cls) return null;
18
+ rows.forEach(el => {
19
+ const val = el[attr.name]?.map?.(c => cls[c] || c) || cls[el[attr.name]] || el[attr.name];
20
+ if (!val) return;
21
+ Object.assign(el, { [val?.color ? `${attr.name}_data` : `${attr.name}_text`]: (val.color ? val : val.text || val) });
22
+ });
23
+
24
+ return null;
25
+ }));
26
+
27
+ return rows;
28
+ }
@@ -1,57 +1,76 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert';
3
-
4
- import build from '../../helper.js';
5
-
6
- test('api table', async (t) => {
7
- const app = await build(t);
8
- // assert.ok(1);
9
- /* await t.test('GET /suggest', async () => {
10
- const res = await app.inject({
11
- method: 'GET',
12
- url: '/api/suggest/test.storage.data',
13
- });
14
- // console.log(res?.body);
15
- const rep = JSON.parse(res?.body);
16
- // console.log(rep.total);
17
- assert.ok(rep.total);
18
- }); */
19
- /* await t.test('GET /data', async () => {
20
- const res = await app.inject({
21
- method: 'GET',
22
- url: '/api/data/test.dataset.table',
23
- });
24
- // console.log(res);
25
- const rep = JSON.parse(res?.body);
26
- // console.log(rep.total);
27
- assert.ok(rep.total);
28
- }); */
29
- /* await t.test('GET /search', async () => {
30
- const res = await app.inject({
31
- method: 'GET',
32
- url: '/api/search?table=test.dataset.table&key=0',
33
- });
34
- const rep = JSON.parse(res?.body);
35
- assert.ok(rep.total);
36
- }); */
37
- await t.test('GET /form', async () => {
38
- const res = await app.inject({
39
- method: 'GET',
40
- url: '/api/form/test.dataset.form',
41
- });
42
- // console.log(res);
43
- const rep = JSON.parse(res?.body);
44
- // console.log(rep.total);
45
- assert.ok(rep);
46
- });
47
- await t.test('GET /filter', async () => {
48
- const res = await app.inject({
49
- method: 'GET',
50
- url: '/api/filter/test.dataset.table',
51
- });
52
- // console.log(res);
53
- const rep = JSON.parse(res?.body);
54
- // console.log(rep.total);
55
- assert.ok(rep);
56
- });
57
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert';
3
+ import pgClients from '../../pg/pgClients.js';
4
+ import init from '../../pg/funcs/init.js';
5
+
6
+ import build from '../../helper.js';
7
+ import config from '../config.js';
8
+
9
+ test('api table', async (t) => {
10
+ const app = await build(t);
11
+ await init(pgClients.client);
12
+
13
+ const bbox = '20.276526313524393 40.6651677831094,35.27752631352439 50.66616778310941';
14
+ const { count = 0 } = await pgClients.client.query(`select count(*) from gis.dataset
15
+ where geom && 'box(${bbox})'::box2d`)
16
+ .then((res) => res.rows[0] || {});
17
+
18
+ await t.test('GET /data (meta bbox / cls)', async () => {
19
+ const res = await app.inject({
20
+ method: 'GET',
21
+ url: `${config.prefix || '/api'}/data/test.dataset.table?bbox=${bbox}&json=1`,
22
+ });
23
+ const json = res.json();
24
+ assert.ok(json?.rows?.length === +count, 'meta bbox - not ok');
25
+ assert.ok(json?.rows?.[0]?.dataset_id_text, 'meta cls - not ok');
26
+ });
27
+
28
+ /* await t.test('GET /suggest', async () => {
29
+ const res = await app.inject({
30
+ method: 'GET',
31
+ url: '/api/suggest/test.storage.data',
32
+ });
33
+ // console.log(res?.body);
34
+ const rep = JSON.parse(res?.body);
35
+ // console.log(rep.total);
36
+ assert.ok(rep.total);
37
+ }); */
38
+ /* await t.test('GET /data', async () => {
39
+ const res = await app.inject({
40
+ method: 'GET',
41
+ url: '/api/data/test.dataset.table',
42
+ });
43
+ // console.log(res);
44
+ const rep = JSON.parse(res?.body);
45
+ // console.log(rep.total);
46
+ assert.ok(rep.total);
47
+ }); */
48
+ /* await t.test('GET /search', async () => {
49
+ const res = await app.inject({
50
+ method: 'GET',
51
+ url: '/api/search?table=test.dataset.table&key=0',
52
+ });
53
+ const rep = JSON.parse(res?.body);
54
+ assert.ok(rep.total);
55
+ }); */
56
+ await t.test('GET /form', async () => {
57
+ const res = await app.inject({
58
+ method: 'GET',
59
+ url: '/api/form/test.dataset.form',
60
+ });
61
+ // console.log(res);
62
+ const rep = JSON.parse(res?.body);
63
+ // console.log(rep.total);
64
+ assert.ok(rep);
65
+ });
66
+ await t.test('GET /filter', async () => {
67
+ const res = await app.inject({
68
+ method: 'GET',
69
+ url: '/api/filter/test.dataset.table',
70
+ });
71
+ // console.log(res);
72
+ const rep = JSON.parse(res?.body);
73
+ // console.log(rep.total);
74
+ assert.ok(rep);
75
+ });
76
+ });