@opengis/gis 0.2.21 → 0.2.23

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.
@@ -0,0 +1,205 @@
1
+ import path from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import {
5
+ readFile, stat, mkdir, writeFile,
6
+ } from 'node:fs/promises';
7
+
8
+ import {
9
+ pgClients, getMeta, metaFormat,
10
+ } from '@opengis/fastify-table/utils.js';
11
+
12
+ import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
13
+
14
+ const systemColumns = ['uid', 'cdate', 'editor_id', 'editor_date', 'created_by', 'created_at', 'updated_by', 'updated_at', 'geom'];
15
+
16
+ /**
17
+ * Повертає JSON дані для реєстру на основі налаштувань з gis.registers
18
+ *
19
+ * @method GET
20
+ * @param {string} params.layer - register_id
21
+ * @param {string} query.page - номер сторінки (default: 1)
22
+ * @param {string} query.limit - кількість записів на сторінку (default: 100)
23
+ * @param {string} query.where - додаткова WHERE умова
24
+ * @param {string} query.sql - повернути SQL запит замість даних
25
+ * @param {boolean} query.nocache - не використовувати кеш
26
+ */
27
+ export default async function jsonData({
28
+ pg = pgClients.client, params = {}, query = {}, unittest,
29
+ }, reply) {
30
+ const { layer } = params;
31
+ const {
32
+ page = 1,
33
+ limit = 100,
34
+ where,
35
+ sql,
36
+ nocache
37
+ } = query;
38
+
39
+ if (!layer) {
40
+ return reply.status(400).send('not enough params: layer (register_id)');
41
+ }
42
+
43
+ const registerId = layer.replace('.json', '');
44
+ const pageNum = parseInt(page, 10) || 1;
45
+ const limitNum = Math.min(parseInt(limit, 10) || 100, 1000); // max 1000
46
+ const offset = (pageNum - 1) * limitNum;
47
+
48
+ if (!pg.pk?.['gis.registers']) {
49
+ return reply.status(404).send('registers table not found');
50
+ }
51
+
52
+ const register = await pg.query(
53
+ `select
54
+ table_name,
55
+ pk,
56
+ query,
57
+ columns,
58
+ is_public,
59
+ is_active,
60
+ "order"
61
+ from gis.registers
62
+ where register_id = $1 and is_active = true and is_public = true`,
63
+ [registerId],
64
+ ).then(el => el.rows?.[0]);
65
+
66
+ if (!register) {
67
+ return reply.status(404).send('register not found or not available');
68
+ }
69
+
70
+ const {
71
+ table_name: table,
72
+ pk,
73
+ query: registerQuery,
74
+ columns,
75
+ order: orderBy,
76
+ } = register;
77
+
78
+ if (!table) {
79
+ return reply.status(400).send('invalid register table_name');
80
+ }
81
+
82
+ if (!pg.pk?.[table]?.length) {
83
+ return reply.status(404).send('table not found');
84
+ }
85
+
86
+ const meta = await getMeta({ pg, table });
87
+ const { columns: metaColumns = [] } = meta || {};
88
+
89
+ let attributeColumns = [];
90
+ if (columns && Array.isArray(columns)) {
91
+ attributeColumns = columns
92
+ .filter(col => col.name && !systemColumns.includes(col.name))
93
+ .map(col => col.name);
94
+ }
95
+
96
+ const columnsFiltered = attributeColumns.length > 0
97
+ ? metaColumns.filter(col => attributeColumns.includes(col.name) && !systemColumns.includes(col.name))
98
+ : metaColumns.filter(col => !systemColumns.includes(col.name));
99
+
100
+ const props = columnsFiltered.map(el =>
101
+ `"${el.name}"${['int4'].includes(el.type) ? '::text' : ''}`
102
+ ).join(', ');
103
+
104
+ if (!props) {
105
+ return reply.status(400).send('no columns to select');
106
+ }
107
+
108
+ const cacheHash = createHash('md5')
109
+ .update([registerId, where, registerQuery, pageNum, limitNum].filter(el => el).join('-'))
110
+ .digest('hex');
111
+
112
+ const today = new Date().toISOString().split('T')[0];
113
+ const filepath = path.join(
114
+ rootFolder,
115
+ `/json/${registerId}/${today}/${cacheHash}.json`,
116
+ );
117
+
118
+ if (existsSync(filepath) && !nocache && !sql && !unittest) {
119
+ const { birthtimeMs = Date.now() } = await stat(filepath);
120
+ const ageInMs = Date.now() - birthtimeMs;
121
+ if (ageInMs < 86400000) {
122
+ const content = await readFile(filepath, 'utf8');
123
+ return reply
124
+ .status(200)
125
+ .header('Content-Type', 'application/json')
126
+ .header('Cache-Control', 'public, max-age=86400')
127
+ .send(content);
128
+ }
129
+ }
130
+
131
+ const whereConditions = [
132
+ registerQuery || '1=1',
133
+ where || 'true',
134
+ ].join(' AND ');
135
+
136
+ const quotedTable = table.split('.').map(el => `"${el}"`).join('.');
137
+
138
+ const countQuery = `
139
+ SELECT COUNT(*) as total
140
+ FROM ${quotedTable}
141
+ WHERE ${whereConditions}
142
+ `;
143
+
144
+ const dataQuery = `
145
+ SELECT "${pk}" as id ${props ? ', ' + props : ''}
146
+ FROM ${quotedTable}
147
+ WHERE ${whereConditions}
148
+ ${orderBy ? `ORDER BY ${orderBy}` : ''}
149
+ LIMIT ${limitNum}
150
+ OFFSET ${offset}
151
+ `;
152
+
153
+ if (sql === '1') return { countQuery, dataQuery };
154
+ if (sql === '2') return filepath.replace(/\\/g, '/');
155
+
156
+ try {
157
+ const [countResult, dataResult] = await Promise.all([
158
+ pg.query(countQuery),
159
+ pg.query(dataQuery),
160
+ ]);
161
+
162
+ const total = parseInt(countResult.rows[0]?.total || 0, 10);
163
+ const rows = dataResult.rows || [];
164
+
165
+ // Обробка класифікаторів
166
+ if (columns && Array.isArray(columns)) {
167
+ const classifiers = columns
168
+ .filter(col => col.data && ['select', 'badge', 'tags', 'integer', 'text', 'text[]'].includes(col.format))
169
+ .reduce((acc, curr) => ({ ...acc, [curr.name]: curr.data }), {});
170
+
171
+ if (Object.keys(classifiers).length > 0) {
172
+ await metaFormat({
173
+ rows,
174
+ table,
175
+ cls: classifiers,
176
+ suffix: true,
177
+ });
178
+ }
179
+ }
180
+
181
+ const result = {
182
+ register_id: registerId,
183
+ total,
184
+ page: pageNum,
185
+ limit: limitNum,
186
+ pages: Math.ceil(total / limitNum),
187
+ data: rows,
188
+ };
189
+
190
+ const jsonString = JSON.stringify(result);
191
+
192
+ if (!nocache && !unittest) {
193
+ await mkdir(path.dirname(filepath), { recursive: true });
194
+ await writeFile(filepath, jsonString, 'utf8');
195
+ }
196
+
197
+ return reply
198
+ .status(200)
199
+ .header('Content-Type', 'application/json')
200
+ .header('Cache-Control', nocache ? 'no-cache' : 'public, max-age=86400')
201
+ .send(jsonString);
202
+ } catch (err) {
203
+ return reply.status(500).send({ error: err.message });
204
+ }
205
+ }
@@ -7,6 +7,8 @@ import mapCatalogAttribute from './controllers/mapCatalogAttribute.js';
7
7
  import rtile from './controllers/rtile.js';
8
8
  import vtile from './controllers/vtile.js';
9
9
  import vtile1 from './vtile1.js';
10
+ import geojson from './controllers/geojson.js';
11
+ import jsonData from './controllers/jsonData.js';
10
12
  import layerList from './controllers/layerList.js';
11
13
 
12
14
  import mapFormat from './controllers/mapFormat.js';
@@ -45,8 +47,8 @@ const schemaInfo = {
45
47
  },
46
48
  };
47
49
 
48
- const publicParams = { config: { policy: 'L0' }, schema: schemaInfo }; // * L0 === public
49
- const privilegedParams = { config: { policy: 'L1', role: 'admin' }, schema: schemaInfo }; // ? just auth or admin
50
+ const publicParams = { config: { policy: 'L0' }, schema: schemaInfo, package: 'gis' }; // * L0 === public
51
+ const privilegedParams = { config: { policy: 'L1', role: 'admin' }, schema: schemaInfo, package: 'gis' }; // ? just auth or admin
50
52
 
51
53
  export default async function route(app) {
52
54
  if (!app.hasRoute({ method: 'GET', url: '/gis-map/:id?' })) {
@@ -108,6 +110,17 @@ export default async function route(app) {
108
110
  console.log('\x1b[34m%s\x1b[0m', 'add vtile from gis');
109
111
  app.get('/vtile/:layer/:lang/:z/:y/:x', publicParams, vtile1);
110
112
  }
113
+
114
+ if (!app.hasRoute({ method: 'GET', url: '/api/geojson/:layer' })) {
115
+ console.log('\x1b[34m%s\x1b[0m', 'add geojson from gis');
116
+ app.get('/geojson/:layer', publicParams, geojson);
117
+ }
118
+
119
+ if (!app.hasRoute({ method: 'GET', url: '/api/json/:layer' })) {
120
+ console.log('\x1b[34m%s\x1b[0m', 'add json from gis');
121
+ app.get('/json/:layer', publicParams, jsonData);
122
+ }
123
+
111
124
  if (!app.hasRoute({ method: 'GET', url: '/api/gis-layer-list' })) {
112
125
  console.log('\x1b[34m%s\x1b[0m', 'add gis-layer-list from gis');
113
126
  app.get('/gis-layer-list', publicParams, layerList);
@@ -107,7 +107,8 @@ export default async function vtile({
107
107
  }[z] || 0.0005;
108
108
 
109
109
  const types = { point: 'ST_Point' /* ,ST_MultiPoint */, polygon: 'ST_Polygon,ST_MultiPolygon' };
110
- const queryMode = ((clusterZoom - z) > 2 ? 1 : null) || ((clusterZoom - z) > 0 ? 2 : null) || 3;
110
+ const clusterZoom1 = style?.clusterZoom || clusterZoom;
111
+ const queryMode = ((clusterZoom1 - z) > 2 ? 1 : null) || ((clusterZoom1 - z) > 0 ? 2 : null) || 3;
111
112
  // console.log(z, clusterZoom, queryMode);
112
113
  const props1 = props.filter((el, idx, arr) => idx === arr.findIndex(item => item.name === el.name));
113
114
  const q = {
@@ -120,11 +121,10 @@ export default async function vtile({
120
121
  )q`,
121
122
  2: `SELECT ST_AsMVT(q, '${layer}', 4096, 'geom','row') as tile
122
123
  FROM (
123
- SELECT floor(random() * 100000 + 1)::int +row_number() over() as row, count(*) as point_count,
124
- ${props?.length ? `${props1.map(prop => `case when count(*)=1 then min(${prop.name.replace(/'/g, "''")}) else null end as "${prop.name.replace(/'/g, "''")}"`).join(',')},` : ''}
124
+ SELECT floor(random() * 100000 + 1)::int +row_number() over() as row, count(*) as point_count,
125
125
  ST_AsMVTGeom(st_transform(st_centroid(ST_Union(geom)),3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,false) as geom
126
126
  FROM (
127
- SELECT ${props?.length ? `${props1.map(prop => prop.name).join(',')},` : ''} geom, ST_ClusterDBSCAN(geom,${koef},1) OVER () AS cluster
127
+ SELECT geom, ST_ClusterDBSCAN(geom,${koef},1) OVER () AS cluster
128
128
  FROM ${table} where ${layerQuery || 'true'} and ${filterData?.q || 'true'} and ${geom} && ${bbox2d} ) j
129
129
  WHERE cluster IS NOT NULL
130
130
  GROUP BY cluster