@opengis/fastify-table 1.2.12 → 1.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.2.12",
3
+ "version": "1.2.14",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "keywords": [
@@ -15,7 +15,7 @@ function getQuery({
15
15
 
16
16
  const mainOperators = ['=', '~', '>', '<'];
17
17
 
18
- const filterQueryArray = decodeURIComponent(filterStr?.replace(/%/g, '%25').replace(/%/g, '\\%')?.replace(/(^,)|(,$)/g, '')).replace(/'/g, '').split(/[;|]/);
18
+ const filterQueryArray = decodeURIComponent(filterStr?.replace(/%/g, '%25').replace(/%/g, '\\%')?.replace(/(^,)|(,$)/g, '')).replace(/'/g, "''").split(/[;|]/);
19
19
 
20
20
  const resultList = [];
21
21
 
@@ -1,169 +1,172 @@
1
- import {
2
- config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, getSelect,
3
- } from '../../../../utils.js';
4
-
5
- const maxLimit = 100;
6
- export default async function dataAPI(req) {
7
- const {
8
- pg, params, query = {}, user = {},
9
- } = req;
10
-
11
- const time = Date.now();
12
-
13
- const { uid } = user;
14
-
15
- const hookData = await applyHook('preData', {
16
- table: params?.table, id: params?.id, user,
17
- });
18
- if (hookData?.message && hookData?.status) {
19
- return { message: hookData?.message, status: hookData?.status };
20
- }
21
-
22
- const loadTable = await getTemplate('table', hookData?.table || params.table);
23
- if (!loadTable) { return { message: 'template not found', status: 404 }; }
24
-
25
- const id = hookData?.id || params?.id;
26
- const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
27
-
28
- if (!actions.includes('view') && !config?.local) {
29
- return { message: 'access restricted', status: 403 };
30
- }
31
-
32
- const {
33
- table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
34
- } = loadTable;
35
-
36
- const tableMeta = await getMeta(table);
37
- if (tableMeta?.view) {
38
- if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
39
- Object.assign(tableMeta, { pk: loadTable?.key });
40
- }
41
- const { pk, columns: dbColumns = [] } = tableMeta || {};
42
-
43
- if (!pk) return { message: `table not found: ${table}`, status: 404 };
44
-
45
- const cols = columns.filter((el) => el.name !== 'geom').map((el) => el.name || el).join(',');
46
- const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
47
- ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
48
- : '';
49
- const columnList = dbColumns.map((el) => el.name || el).join(',');
50
- 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('') || '';
51
- const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
52
- const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
53
-
54
- if (params.id && columnList.includes(params.id)) {
55
- return gisIRColumn({
56
- pg,
57
- layer: params.table,
58
- column: params.id,
59
- sql: query.sql,
60
- filter: query.filter,
61
- search: query.search,
62
- state: query.state,
63
- custom: query.custom,
64
- });
65
- }
66
-
67
- const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
68
- const fData = checkFilter ? await getFilterSQL({
69
- table: params.table,
70
- filter: query.filter,
71
- search: query.search,
72
- state: query.state,
73
- custom: query.custom,
74
- json: 1,
75
- }) : {};
76
-
77
- const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
78
-
79
- const limit = Math.min(maxLimit, +(query.limit || 20));
80
-
81
- const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
82
- // id, query, filter
83
- const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
84
-
85
- const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
86
- const search = loadTable.meta?.search && query.search
87
- ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%').replace(/'/g, "''")}%'`).join(' or ')})`
88
- : null;
89
- const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
90
- const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
91
- 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;
92
-
93
- const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
94
- const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
95
-
96
- // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
97
- const q = `select ${pk ? `"${pk}" as id,` : ''}
98
- ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
99
- ${metaCols}
100
-
101
- ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
102
- from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
103
- ${sqlTable}
104
- ${cardSqlTable}
105
- where ${where.join(' and ') || 'true'}
106
- ${order} ${offset} limit ${limit}`
107
- .replace(/{{uid}}/g, uid);
108
-
109
- // if (user?.user_type === 'superadmin') console.log(q);
110
-
111
- if (query.sql === '1') { return q; }
112
-
113
- const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
114
-
115
- const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
116
-
117
- const aggColumns = columns.filter((el) => el.agg).reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.agg }), {});
118
- const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type) && aggColumns[el.name]);
119
- const qCount = `select
120
- count(*)::int as total,
121
- count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
122
- ${aggregates.length ? `,${aggregates.map((el) => `${aggColumns[el.name]}(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
123
- from ${table} t ${sqlTable}
124
- where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
125
- .replace(/{{uid}}/g, uid);
126
-
127
- if (query.sql === '2') { return qCount; }
128
-
129
- const counts = keyQuery || hookData?.id || params.id
130
- ? { total: rows.length, filtered: rows.length }
131
- : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
132
-
133
- const { total, filtered } = counts;
134
- const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
135
-
136
- await metaFormat({ rows, table: hookData?.table || params.table });
137
-
138
- const status = [];
139
- if (loadTable.meta?.status) {
140
- const statusColumn = loadTable.meta?.cls?.[loadTable.meta?.status]
141
- ? { name: loadTable.meta?.status, data: loadTable.meta?.cls?.[loadTable.meta?.status] }
142
- : loadTable.columns.find(col => col.name === loadTable.meta?.status) || {};
143
-
144
- const statusCls = statusColumn.data || statusColumn.option;
145
- const statusClsData = statusCls ? await getSelect(statusCls, pg) : {};
146
- statusClsData?.arr
147
- ?.forEach(el => status.push({ ...el, count: rows.filter(row => el.id === row[statusColumn.name]).length }));
148
- }
149
-
150
- const res = {
151
- time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, status, rows, meta, columns, filters,
152
- };
153
-
154
- // console.log({ add: loadTable.table, form: loadTable.form });
155
- if (uid && actions.includes('add')) {
156
- const addTokens = setToken({
157
- ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
158
- uid,
159
- array: 1,
160
- });
161
- Object.assign(res, { addToken: addTokens[0] });
162
- }
163
-
164
- const result = await applyHook('afterData', {
165
- table: loadTable.table, payload: res, user,
166
- });
167
-
168
- return result || res;
169
- }
1
+ import {
2
+ config, getTemplate, getFilterSQL, getMeta, metaFormat, getAccess, setToken, gisIRColumn, applyHook, handlebars, getSelect,
3
+ } from '../../../../utils.js';
4
+
5
+ const maxLimit = 100;
6
+ export default async function dataAPI(req) {
7
+ const {
8
+ pg, params, query = {}, user = {},
9
+ } = req;
10
+
11
+ const time = Date.now();
12
+
13
+ const { uid } = user;
14
+
15
+ const hookData = await applyHook('preData', {
16
+ table: params?.table, id: params?.id, user,
17
+ });
18
+ if (hookData?.message && hookData?.status) {
19
+ return { message: hookData?.message, status: hookData?.status };
20
+ }
21
+
22
+ const loadTable = await getTemplate('table', hookData?.table || params.table);
23
+ if (!loadTable) { return { message: 'template not found', status: 404 }; }
24
+
25
+ const id = hookData?.id || params?.id;
26
+ const { actions = [], query: accessQuery } = await getAccess({ table: hookData?.table || params.table, id, user }) || {};
27
+
28
+ if (!actions.includes('view') && !config?.local) {
29
+ return { message: 'access restricted', status: 403 };
30
+ }
31
+
32
+ const {
33
+ table, columns = [], sql, cardSql, filters, form, meta, sqlColumns, public: ispublic,
34
+ } = loadTable;
35
+
36
+ const tableMeta = await getMeta(table);
37
+ if (tableMeta?.view) {
38
+ if (!loadTable?.key) return { message: `key not found: ${table}`, status: 404 };
39
+ Object.assign(tableMeta, { pk: loadTable?.key });
40
+ }
41
+ const { pk, columns: dbColumns = [] } = tableMeta || {};
42
+
43
+ if (!pk) return { message: `table not found: ${table}`, status: 404 };
44
+
45
+ const columnList = dbColumns.map((el) => el.name || el).join(',');
46
+ const sqlTable = sql?.filter?.((el) => !el?.disabled && el?.sql?.replace && (!el.sql.includes('{{uid}}') || uid)).map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ${el.name || `t${i}`} on 1=1 `)?.join('') || '';
47
+ const cardSqlFiltered = hookData?.id || params.id ? (cardSql?.filter?.((el) => !el?.disabled && el?.name && el?.sql?.replace) || []) : [];
48
+ const cardSqlTable = cardSqlFiltered.length ? cardSqlFiltered.map((el, i) => ` left join lateral (${el.sql.replace('{{uid}}', uid)}) ct${i} on 1=1 `).join('\n') || '' : '';
49
+
50
+ const { fields } = await pg.queryCache(`select * from ${table} t ${sqlTable} ${cardSqlTable} limit 0`);
51
+ const dbColumnsTable = fields.map(el => el.name);
52
+ const cols = columns.filter((el) => el.name !== 'geom' && dbColumnsTable.includes(el.name)).map((el) => el.name || el).join(',');
53
+ const metaCols = Object.keys(loadTable?.meta?.cls || {}).filter((el) => !cols.includes(el)).length
54
+ ? `,${Object.keys(loadTable?.meta?.cls || {})?.filter((el) => !cols.includes(el)).join(',')}`
55
+ : '';
56
+
57
+ if (params.id && columnList.includes(params.id)) {
58
+ return gisIRColumn({
59
+ pg,
60
+ layer: params.table,
61
+ column: params.id,
62
+ sql: query.sql,
63
+ filter: query.filter,
64
+ search: query.search,
65
+ state: query.state,
66
+ custom: query.custom,
67
+ });
68
+ }
69
+
70
+ const checkFilter = [query.filter, query.search, query.state, query.custom].filter((el) => el).length;
71
+ const fData = checkFilter ? await getFilterSQL({
72
+ table: params.table,
73
+ filter: query.filter,
74
+ search: query.search,
75
+ state: query.state,
76
+ custom: query.custom,
77
+ json: 1,
78
+ }) : {};
79
+
80
+ const keyQuery = query.key && loadTable.key && !(hookData?.id || params.id) ? `${loadTable.key}=$1` : null;
81
+
82
+ const limit = Math.min(maxLimit, +(query.limit || 20));
83
+
84
+ const offset = query.page && query.page > 0 ? ` offset ${(query.page - 1) * limit}` : '';
85
+ // id, query, filter
86
+ const [orderColumn, orderDir] = (query.order || loadTable.order || '').split(/[- ]/);
87
+
88
+ const order = columnList.includes(orderColumn) && orderColumn?.length ? `order by ${orderColumn} ${query.desc || orderDir === 'desc' ? 'desc' : ''}` : '';
89
+ const search = loadTable.meta?.search && query.search
90
+ ? `(${loadTable.meta?.search.split(',').map(el => `${el} ilike '%${query.search.replace(/%/g, '\\%').replace(/'/g, "''")}%'`).join(' or ')})`
91
+ : null;
92
+ const queryBbox = query?.bbox ? query.bbox.replace(/ /g, ',').split(',')?.map((el) => el - 0) : [];
93
+ const queryPolyline = meta?.bbox && query?.polyline ? `ST_Contains(ST_MakePolygon(ST_LineFromEncodedPolyline('${query?.polyline}')),${meta.bbox})` : undefined;
94
+ 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;
95
+
96
+ const interfaceQuery = params?.query ? await handlebars.compile(params?.query)({ user, uid }) : undefined;
97
+ const where = [(hookData?.id || params.id ? ` "${pk}" = $1` : null), keyQuery, loadTable.query, fData.q, search, accessQuery || '1=1', bbox, queryPolyline, interfaceQuery].filter((el) => el).filter((el) => (user?.user_type === 'superadmin' ? !el.includes('{{uid}}') : true));
98
+
99
+ // const cardColumns = cardSqlFiltered.length ? `,${cardSqlFiltered.map((el) => el.name)}` : '';
100
+ const q = `select ${pk ? `"${pk}" as id,` : ''}
101
+ ${params.id || query.key ? '*' : sqlColumns || cols || '*'}
102
+ ${metaCols}
103
+
104
+ ${dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''}
105
+ from (select * from ${table} where ${sqlTable ? 'true' : (where.join(' and ') || 'true')} ${order}) t
106
+ ${sqlTable}
107
+ ${params.id ? cardSqlTable : ''}
108
+ where ${where.join(' and ') || 'true'}
109
+ ${order} ${offset} limit ${limit}`
110
+ .replace(/{{uid}}/g, uid);
111
+
112
+ // if (user?.user_type === 'superadmin') console.log(q);
113
+
114
+ if (query.sql === '1') { return q; }
115
+
116
+ const { rows } = await pg.query(q, (hookData?.id || params.id ? [hookData?.id || params.id] : null) || (query.key && loadTable.key ? [query.key] : []));
117
+
118
+ const filterWhere = [fData.q, search, bbox, queryPolyline, interfaceQuery, loadTable.query].filter((el) => el);
119
+
120
+ const aggColumns = columns.filter((el) => el.agg).reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.agg }), {});
121
+ const aggregates = dbColumns.map((el) => ({ name: el.name, type: pg.pgType[el.dataTypeID] })).filter((el) => ['numeric', 'double precision'].includes(el.type) && aggColumns[el.name]);
122
+ const qCount = `select
123
+ count(*)::int as total,
124
+ count(*) FILTER(WHERE ${filterWhere.join(' and ') || 'true'})::int as filtered
125
+ ${aggregates.length ? `,${aggregates.map((el) => `${aggColumns[el.name]}(${el.name}) FILTER(WHERE ${filterWhere.join(' and ') || 'true'}) as ${el.name}`).join(',')}` : ''}
126
+ from ${table} t ${sqlTable}
127
+ where ${[loadTable.query, accessQuery].filter(el => el).join(' and ') || 'true'} `
128
+ .replace(/{{uid}}/g, uid);
129
+
130
+ if (query.sql === '2') { return qCount; }
131
+
132
+ const counts = keyQuery || hookData?.id || params.id
133
+ ? { total: rows.length, filtered: rows.length }
134
+ : await pg.queryCache(qCount, { table: loadTable.table, time: 5 }).then(el => el?.rows[0] || {});
135
+
136
+ const { total, filtered } = counts;
137
+ const agg = Object.keys(counts).filter(el => !['total', 'filtered'].includes(el)).reduce((acc, el) => ({ ...acc, [el]: counts[el] }), {});
138
+
139
+ await metaFormat({ rows, table: hookData?.table || params.table });
140
+
141
+ const status = [];
142
+ if (loadTable.meta?.status) {
143
+ const statusColumn = loadTable.meta?.cls?.[loadTable.meta?.status]
144
+ ? { name: loadTable.meta?.status, data: loadTable.meta?.cls?.[loadTable.meta?.status] }
145
+ : loadTable.columns.find(col => col.name === loadTable.meta?.status) || {};
146
+
147
+ const statusCls = statusColumn.data || statusColumn.option;
148
+ const statusClsData = statusCls ? await getSelect(statusCls, pg) : {};
149
+ statusClsData?.arr
150
+ ?.forEach(el => status.push({ ...el, count: rows.filter(row => el.id === row[statusColumn.name]).length }));
151
+ }
152
+
153
+ const res = {
154
+ time: Date.now() - time, public: ispublic, card: loadTable.card, actions, total, filtered, count: rows.length, pk, form, agg, status, rows, meta, columns, filters,
155
+ };
156
+
157
+ // console.log({ add: loadTable.table, form: loadTable.form });
158
+ if (uid && actions.includes('add')) {
159
+ const addTokens = setToken({
160
+ ids: [JSON.stringify({ table: hookData?.table || params.table, form: loadTable.form })],
161
+ uid,
162
+ array: 1,
163
+ });
164
+ Object.assign(res, { addToken: addTokens[0] });
165
+ }
166
+
167
+ const result = await applyHook('afterData', {
168
+ table: loadTable.table, payload: res, user,
169
+ });
170
+
171
+ return result || res;
172
+ }