@opengis/gis 0.2.20 → 0.2.22

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 (155) hide show
  1. package/README.md +5 -5
  2. package/dist/index.css +1 -1
  3. package/dist/index.js +1691 -1663
  4. package/dist/index.umd.cjs +20 -20
  5. package/module/cls.json +6 -6
  6. package/module/gis/card/gis.maps.table/index.yml +14 -14
  7. package/module/gis/card/gis.maps.table/main_info.hbs +25 -25
  8. package/module/gis/card/gis.maps.table/maps_layers.hbs +19 -19
  9. package/module/gis/card/gis.metadata.table/index.yml +22 -22
  10. package/module/gis/card/gis.metadata.table/main_info.hbs +20 -20
  11. package/module/gis/card/gis.metadata.table/metadata_info.hbs +27 -27
  12. package/module/gis/card/gis.metadata.table/other.hbs +25 -25
  13. package/module/gis/card/gis.rasters.table/index.yml +11 -11
  14. package/module/gis/card/gis.rasters.table/main_info.hbs +27 -27
  15. package/module/gis/card/gis.registers.table/cls.hbs +36 -36
  16. package/module/gis/card/gis.registers.table/columns.hbs +89 -89
  17. package/module/gis/card/gis.registers.table/filters.hbs +80 -80
  18. package/module/gis/card/gis.registers.table/index.yml +23 -23
  19. package/module/gis/card/gis.registers.table/main_info.hbs +35 -35
  20. package/module/gis/card/gis.registers.table/source.hbs +45 -45
  21. package/module/gis/card/gis.services.table/attributes.hbs +91 -91
  22. package/module/gis/card/gis.services.table/filters.hbs +83 -83
  23. package/module/gis/card/gis.services.table/index.yml +25 -25
  24. package/module/gis/card/gis.services.table/main_info.hbs +27 -27
  25. package/module/gis/card/gis.services.table/source.hbs +25 -25
  26. package/module/gis/cls/bool.yes_no.json +12 -12
  27. package/module/gis/cls/encoding.json +14 -14
  28. package/module/gis/cls/geom_type.json +14 -14
  29. package/module/gis/cls/gis.column_type.json +34 -34
  30. package/module/gis/cls/gis.column_view_type.json +26 -26
  31. package/module/gis/cls/gis.filter_type.json +22 -22
  32. package/module/gis/cls/language.json +10 -10
  33. package/module/gis/cls/meta.service_type.json +42 -42
  34. package/module/gis/cls/ogc.service.json +21 -21
  35. package/module/gis/cls/service_type.json +42 -42
  36. package/module/gis/cls/source_type.json +10 -10
  37. package/module/gis/cls/standarts.json +6 -6
  38. package/module/gis/cls/topic_category.json +106 -106
  39. package/module/gis/cls/update_frequency.json +29 -29
  40. package/module/gis/cls/view.json +21 -21
  41. package/module/gis/form/gis.cartocss.form.json +46 -0
  42. package/module/gis/form/gis.group_list.form.json +17 -17
  43. package/module/gis/form/gis.maps.form.json +64 -64
  44. package/module/gis/form/gis.metadata.form.json +240 -240
  45. package/module/gis/form/gis.ogc_service.form.json +40 -40
  46. package/module/gis/form/gis.rasters.form.json +99 -99
  47. package/module/gis/form/gis.registers.form.json +110 -110
  48. package/module/gis/form/gis.registers_column.form.json +84 -84
  49. package/module/gis/form/gis.registers_filter.form.json +65 -65
  50. package/module/gis/form/gis.services.form.json +120 -120
  51. package/module/gis/form/gis.services_attributes.form.json +75 -75
  52. package/module/gis/form/gis.services_filter.form.json +65 -65
  53. package/module/gis/menu.json +43 -43
  54. package/module/gis/select/pg.columns.parent.sql +6 -6
  55. package/module/gis/select/pg.table_name.sql +17 -17
  56. package/module/gis/select/service_id.sql +1 -1
  57. package/module/gis/table/gis.cartocss.table.json +61 -0
  58. package/module/gis/table/gis.group_list.table.json +35 -35
  59. package/module/gis/table/gis.maps.table.json +69 -69
  60. package/module/gis/table/gis.metadata.table.json +70 -70
  61. package/module/gis/table/gis.ogc_service.table.json +97 -97
  62. package/module/gis/table/gis.rasters.table.json +97 -97
  63. package/module/gis/table/gis.registers.table.json +79 -79
  64. package/module/gis/table/gis.services.table.json +99 -99
  65. package/module/gis/table/site.gis.registers.table.json +88 -88
  66. package/module/gis/table/site.gis.services.table.json +106 -106
  67. package/module/gis/templates/ISO19136_2017_gml_template.xml +330 -330
  68. package/module/gis/tokens.yml +5 -5
  69. package/module/test/cls/bp_build_type.json +37 -37
  70. package/module/test/cls/doc_status.json +31 -31
  71. package/module/test/cls/ts.temp_status.json +18 -18
  72. package/module/test/cls/ts.temp_structure.ts_class.json +49 -49
  73. package/module/test/cls/ts.temp_type.json +9 -9
  74. package/module/test/layer/bp.json +59 -59
  75. package/module/test/layer/bp1.yml +33 -33
  76. package/module/test/layer/individual.yml +53 -53
  77. package/module/test/layer/ts.linking_passport.yml +55 -55
  78. package/module/test/layer/ts.temp_structure.yml +50 -50
  79. package/module/test/map/addr.yml +21 -21
  80. package/module/test/map/bp_myo.json +43 -43
  81. package/module/test/map/bpf.json +43 -43
  82. package/module/test/map/main.json +36 -36
  83. package/module/test/map/mbd.json +91 -91
  84. package/module/test/map/ts.json +52 -52
  85. package/module/test/select/address_id.json +2 -2
  86. package/module/test/select/address_id.sql +7 -7
  87. package/module/test/select/core.user_uid.sql +1 -1
  88. package/module/test/table/data_address.street.table.json +69 -69
  89. package/module/test/table/data_bp_myo.bp.table.json +122 -122
  90. package/package.json +69 -69
  91. package/plugin.js +44 -44
  92. package/server/migrations/maps.sql +30 -30
  93. package/server/migrations/ogc.sql +106 -106
  94. package/server/migrations/rasters.sql +263 -263
  95. package/server/migrations/services.sql +247 -247
  96. package/server/migrations/widgets.sql +20 -20
  97. package/server/plugins/crons.js +21 -21
  98. package/server/plugins/mapnik/funcs/createXML.js +72 -72
  99. package/server/plugins/mapnik/funcs/gdalWrapper.js +72 -72
  100. package/server/plugins/mapnik/funcs/map.proto +241 -241
  101. package/server/plugins/mapnik/funcs/mapnik.js +106 -106
  102. package/server/plugins/mapnik/funcs/rasterConfig.js +11 -11
  103. package/server/plugins/mapnik/funcs/rasterExists.js +20 -20
  104. package/server/plugins/mapnik/funcs/rasterInfo.js +109 -109
  105. package/server/plugins/mapnik/funcs/rasterVrt.js +55 -55
  106. package/server/plugins/mapnik/funcs/rasterXML.js +65 -65
  107. package/server/plugins/mapnik/funcs/rootFolder.mjs +8 -8
  108. package/server/plugins/mapnik/utils/map.proto +241 -241
  109. package/server/plugins/vite.js +74 -74
  110. package/server/routes/gis/dashboard.js +29 -0
  111. package/server/routes/gis/index.mjs +61 -59
  112. package/server/routes/gis/metadata/metadataXML.js +13 -13
  113. package/server/routes/gis/ogc/map.info.point.js +124 -124
  114. package/server/routes/gis/registers/add.registry.js +35 -35
  115. package/server/routes/gis/registers/del.registry.js +14 -14
  116. package/server/routes/gis/registers/funcs/classifiers.js +100 -100
  117. package/server/routes/gis/registers/funcs/columns.js +4 -4
  118. package/server/routes/gis/registers/funcs/content.type.js +9 -9
  119. package/server/routes/gis/registers/funcs/get.info.js +89 -89
  120. package/server/routes/gis/registers/funcs/handleRegistryRequest.js +133 -122
  121. package/server/routes/gis/registers/gis.export.js +148 -148
  122. package/server/routes/gis/registers/gis.registry.js +70 -38
  123. package/server/routes/gis/registers/gis.registry.list.js +59 -59
  124. package/server/routes/gis/registers/insert.columns.js +107 -107
  125. package/server/routes/gis/registers/insert.filters.js +110 -110
  126. package/server/routes/gis/registers/map.registry.js +79 -79
  127. package/server/routes/gis/services/add.service.js +64 -64
  128. package/server/routes/gis/services/del.service.js +12 -12
  129. package/server/routes/gis/services/get.layer.geom.js +27 -27
  130. package/server/routes/gis/services/get.services.col.js +33 -33
  131. package/server/routes/gis/services/get.services.js +84 -84
  132. package/server/routes/gis/services/legend.auto.js +77 -77
  133. package/server/routes/map/controllers/geojson.js +187 -0
  134. package/server/routes/map/controllers/jsonData.js +205 -0
  135. package/server/routes/map/controllers/layerList.js +60 -60
  136. package/server/routes/map/controllers/map.js +123 -123
  137. package/server/routes/map/controllers/mapCatalog.js +72 -72
  138. package/server/routes/map/controllers/mapCatalogAttribute.js +55 -55
  139. package/server/routes/map/controllers/mapFeatures.js +128 -128
  140. package/server/routes/map/controllers/mapFormat.js +83 -83
  141. package/server/routes/map/controllers/mapTiles.js +152 -152
  142. package/server/routes/map/controllers/maps.js +15 -15
  143. package/server/routes/map/controllers/marker_icon.js +43 -43
  144. package/server/routes/map/controllers/rtile.js +134 -134
  145. package/server/routes/map/controllers/vtile.js +172 -172
  146. package/server/routes/map/index.mjs +142 -129
  147. package/server/routes/map/maps/add.map.js +41 -41
  148. package/server/routes/map/maps/del.map.js +18 -18
  149. package/server/routes/map/maps/get.map.js +86 -86
  150. package/server/routes/map/vtile1.js +170 -170
  151. package/server/routes/map/widgets/add.widget.js +38 -38
  152. package/server/routes/map/widgets/del.widget.js +22 -22
  153. package/server/routes/map/widgets/get.widget.js +40 -40
  154. package/server/routes/root.mjs +3 -3
  155. package/utils.js +11 -11
@@ -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
+ }
@@ -1,60 +1,60 @@
1
- import {
2
- config, pgClients, yml2json, getTemplates, getTemplate,
3
- } from '@opengis/fastify-table/utils.js';
4
-
5
- export default async function layerList({
6
- pg = pgClients.client, query = {}, user = {},
7
- }, reply) {
8
- const { sql } = query;
9
- const layers = getTemplates('layer');
10
- const files = Promise.all(layers.map(async (el) => {
11
- const layer = await getTemplate('layer', el[0]);
12
- return layer;
13
- }));
14
-
15
- if (!pg.pk?.['gis.services']) {
16
- return files;
17
- // return reply.status(404).send('services table not found');
18
- }
19
-
20
- const q = `
21
- select service_id as id, name, category, style, bbox::box2d as extent, st_asgeojson(bbox)::json as geom, null as url, coalesce(service_type, 'vtile') as service, group_id,
22
- popup, card, filters, style, source_path
23
- from gis.services where is_active and ${!user.uid ? 'is_public' : '1=1'}
24
- union all
25
- select ogc_service_id as id, name, category, null as style, geom::box2d as extent, st_asgeojson(geom)::json as geom, url, 'ogc' as service, group_id,
26
- null as popup, null as card, null as filters, null as style, table_name as source_path
27
- from gis.ogc_service where enabled and ${!user.uid ? 'ispublic' : '1=1'}
28
- `;
29
-
30
- if (user.uid && sql) return q;
31
-
32
- const rows = await pg.query(q).then(el => el.rows || []);
33
-
34
- const totals = pg.queryCache ? await pg.queryCache('select json_object_agg(oid::regclass, reltuples) from pg_class')
35
- .then(el => el.rows?.[0]?.json_object_agg || {}) : {};
36
- rows.filter(row => row.source_path).forEach(row => Object.assign(row, { count: totals[row.source_path] || 0 }));
37
-
38
- const groupIds = rows.map(el => el.group_id).filter(Boolean);
39
- const groupNames = groupIds.length ? await pg.query('select json_object_agg(group_id,group_name) from gis.group_list where group_id=any($1)', [groupIds]).then(el => el.rows?.[0]?.json_object_agg || {}) : {};
40
- rows.filter(el => el.group_id).forEach(row => Object.assign(row, { group_name: groupNames[row.group_id] }));
41
-
42
- if (!rows.length) {
43
- return reply.status(200).send([]);
44
- }
45
-
46
- // parse service style
47
- rows.forEach(row => Object.assign(row, { style: row.style ? yml2json(row.style) : null }));
48
- // assign service url
49
- rows.filter(row => row.service !== 'ogc').forEach(row => Object.assign(row, { url: `${config.prefix || '/api'}/vtile/${row.id}/ua/{z}/{x}/{y}.vmt` }));
50
- // parse extent string to number[]
51
- rows.filter(row => row.extent).forEach(row => Object.assign(row, {
52
- extent: row.extent.match(/BOX\(([^)]+)\)/)?.[1]
53
- ?.replace?.(/ /g, ',')
54
- ?.split?.(','),
55
- }));
56
-
57
- // return files;
58
-
59
- return reply.status(200).send(rows.concat(files));
60
- }
1
+ import {
2
+ config, pgClients, yml2json, getTemplates, getTemplate,
3
+ } from '@opengis/fastify-table/utils.js';
4
+
5
+ export default async function layerList({
6
+ pg = pgClients.client, query = {}, user = {},
7
+ }, reply) {
8
+ const { sql } = query;
9
+ const layers = getTemplates('layer');
10
+ const files = Promise.all(layers.map(async (el) => {
11
+ const layer = await getTemplate('layer', el[0]);
12
+ return layer;
13
+ }));
14
+
15
+ if (!pg.pk?.['gis.services']) {
16
+ return files;
17
+ // return reply.status(404).send('services table not found');
18
+ }
19
+
20
+ const q = `
21
+ select service_id as id, name, category, style, bbox::box2d as extent, st_asgeojson(bbox)::json as geom, null as url, coalesce(service_type, 'vtile') as service, group_id,
22
+ popup, card, filters, style, source_path
23
+ from gis.services where is_active and ${!user.uid ? 'is_public' : '1=1'}
24
+ union all
25
+ select ogc_service_id as id, name, category, null as style, geom::box2d as extent, st_asgeojson(geom)::json as geom, url, 'ogc' as service, group_id,
26
+ null as popup, null as card, null as filters, null as style, table_name as source_path
27
+ from gis.ogc_service where enabled and ${!user.uid ? 'ispublic' : '1=1'}
28
+ `;
29
+
30
+ if (user.uid && sql) return q;
31
+
32
+ const rows = await pg.query(q).then(el => el.rows || []);
33
+
34
+ const totals = pg.queryCache ? await pg.queryCache('select json_object_agg(oid::regclass, reltuples) from pg_class')
35
+ .then(el => el.rows?.[0]?.json_object_agg || {}) : {};
36
+ rows.filter(row => row.source_path).forEach(row => Object.assign(row, { count: totals[row.source_path] || 0 }));
37
+
38
+ const groupIds = rows.map(el => el.group_id).filter(Boolean);
39
+ const groupNames = groupIds.length ? await pg.query('select json_object_agg(group_id,group_name) from gis.group_list where group_id=any($1)', [groupIds]).then(el => el.rows?.[0]?.json_object_agg || {}) : {};
40
+ rows.filter(el => el.group_id).forEach(row => Object.assign(row, { group_name: groupNames[row.group_id] }));
41
+
42
+ if (!rows.length) {
43
+ return reply.status(200).send([]);
44
+ }
45
+
46
+ // parse service style
47
+ rows.forEach(row => Object.assign(row, { style: row.style ? yml2json(row.style) : null }));
48
+ // assign service url
49
+ rows.filter(row => row.service !== 'ogc').forEach(row => Object.assign(row, { url: `${config.prefix || '/api'}/vtile/${row.id}/ua/{z}/{x}/{y}.vmt` }));
50
+ // parse extent string to number[]
51
+ rows.filter(row => row.extent).forEach(row => Object.assign(row, {
52
+ extent: row.extent.match(/BOX\(([^)]+)\)/)?.[1]
53
+ ?.replace?.(/ /g, ',')
54
+ ?.split?.(','),
55
+ }));
56
+
57
+ // return files;
58
+
59
+ return reply.status(200).send(rows.concat(files));
60
+ }
@@ -1,124 +1,124 @@
1
- import path from 'node:path';
2
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
- import { fileURLToPath } from 'url';
4
- import { createHash } from 'node:crypto';
5
-
6
- import { config, getMeta, getTemplate, getTemplateSync, pgClients, getSelect, getSelectVal, getTemplatePath } from '@opengis/fastify-table/utils.js';
7
-
8
- const { prefix = '/api' } = config;
9
- const dirname = path.dirname(fileURLToPath(import.meta.url));
10
-
11
- const maps = getTemplatePath('map')?.map?.(el => {
12
- const { name = el[0] } = getTemplateSync('map', el[0]) || {};
13
- return { slug: el[0], name };
14
- });
15
-
16
- async function processObject(loadTemplate, pg = pgClients.client, unittest) {
17
- // default center for all maps (frontend dependends on it)
18
- const { bbox = [], center = [30, 50] } = loadTemplate?.source_path && pg.pk?.[loadTemplate.source_path]
19
- ? await pg.query(`select
20
- array[ST_XMin(env), ST_YMin(env), ST_XMax(env),ST_YMax(env)] as bbox,
21
- st_asgeojson(st_centroid(env))::json->'coordinates' as center
22
- from ( select st_extent(geom) as env from ${loadTemplate.source_path} where ${loadTemplate.source_query || '1=1'})q`
23
- ).then(el => el.rows?.[0] || {})
24
- : {};
25
- loadTemplate.map = { bbox, center };
26
-
27
-
28
- if (!loadTemplate?.widgets?.length) return;
29
- // add legend if not exists in widget
30
- const idx = loadTemplate.widgets.findIndex(el => el.type === 'attribute_style');
31
- const { source_path: attrTable, attribute, cls: clsName, legend = [], colors } = loadTemplate.widgets.find(el => el.type === 'attribute_style')?.config || {};
32
- const colors1 = colors || ['red', 'black', 'blue', 'green', 'orange'];
33
-
34
- if (!legend?.length && attribute && attrTable) {
35
- const { columns = {} } = await getMeta({ pg, table: attrTable });
36
- const { dataTypeID = 0 } = columns.find(item => item.name === attribute) || {};
37
- const q = pg.pgType?.[dataTypeID]?.includes?.('[]')
38
- ? `select unnest(${attribute})::text as id,count(*) from ${attrTable} group by unnest(${attribute}) limit 100`
39
- : `select ${attribute}::text as id,count(*) from ${attrTable} group by ${attribute} limit 100`;
40
-
41
- if (config.trace || unittest) console.log(q);
42
- const countArr = await pg.queryCache(q, { time: 5 });
43
-
44
- const ids = countArr.rows.map(item => item.id);
45
-
46
- const cls = await getSelect(clsName, pg);
47
- const clsData = await getSelectVal({ pg, values: ids, cls: clsName });
48
-
49
- const options = countArr.rows.map((cel, idx) => {
50
- const data = cls?.arr?.find?.(c => c.id?.toString?.() === cel.id?.toString?.()) || { text: clsData?.[cel.id]?.text || clsData?.[cel.id] };
51
- const color = (colors?.length ? colors1[idx % colors1.length] : null) || data?.color || colors1[idx % colors1.length];
52
- return { ...cel, ...data, color };
53
- });
54
- loadTemplate.widgets[idx].config.legend = options;
55
- }
56
-
57
-
58
- const { source_path: table, filters = [] } = loadTemplate.widgets.find(el => el.type === 'filters')?.config || {};
59
-
60
- filters.forEach(el => Object.assign(el, { name: el.name || el.id }));
61
-
62
- // md5 hash for suggest security
63
- filters.filter(el => el.type?.toLowerCase() === 'select').map(async (el) => {
64
- const hash = createHash('md5').update([table, el.name].join()).digest('hex');
65
- el.api = `${prefix}/suggest/hash-${hash}`;
66
- const filepath = path.join(dirname, `../../../../log/suggest/${hash}.json`);
67
- if (existsSync(filepath)) { return; };
68
- mkdirSync(path.dirname(filepath), { recursive: true });
69
- writeFileSync(filepath, JSON.stringify({ table, column: el.name }), { encoding: 'utf8' });
70
- });
71
-
72
- // add options to filters
73
- if (filters.filter(el => el.data).length && table) {
74
- const { columns = {} } = await getMeta({ pg, table });
75
- await Promise.all(filters.filter(el => el.data && el.name).map(async (el) => {
76
- const { dataTypeID = 0 } = columns.find(item => item.name === el.name) || {};
77
- const q = pg.pgType?.[dataTypeID]?.includes?.('[]')
78
- ? `select unnest(${el.name})::text as id,count(*) from ${table} group by unnest(${el.name}) limit 100`
79
- : `select ${el.name}::text as id,count(*) from ${table} group by ${el.name} limit 100`;
80
-
81
- if (config.trace || unittest) console.log(q);
82
- const countArr = await pg.queryCache(q, { time: 5 });
83
-
84
- const ids = countArr.rows.map(item => item.id);
85
-
86
- const cls = await getSelect(el.data, pg);
87
- const clsData = await getSelectVal({ pg, values: ids, name: el.data });
88
-
89
- const options = countArr.rows.map(cel => {
90
- const data = cls?.arr?.find?.(c => c.id?.toString?.() === cel.id?.toString?.()) || { text: clsData[cel.id]?.text || clsData[cel.id] };
91
- return { ...cel, ...data };
92
- });
93
- Object.assign(el, { options });
94
- }));
95
- }
96
- return loadTemplate;
97
- }
98
-
99
- export default async function map({ pg = pgClients.client, params = {}, unittest }, reply) {
100
- const { slug } = params;
101
-
102
- const loadTemplate = await getTemplate('map', slug);
103
-
104
- if (!loadTemplate) {
105
- return reply.status(404).send('map not found');
106
- }
107
-
108
- if (!Array.isArray(loadTemplate)) {
109
- await processObject(loadTemplate, pg, unittest);
110
- return { ...loadTemplate, maps };
111
- }
112
-
113
- const index = loadTemplate?.find?.(el => el[0].split('.').shift() === 'index')?.[1];
114
-
115
- if (!index) {
116
- return reply.status(404).send('map index not found');
117
- }
118
-
119
- await processObject(index, pg, unittest);
120
-
121
- const layers = loadTemplate?.filter?.(el => el[0].split('.').shift() !== 'index')?.map(el => ({ ...el[1], id: el[0].replace('.yml', '').replace('.json', '') }));
122
-
123
- return reply.status(200).send({ ...index, layers, maps });
1
+ import path from 'node:path';
2
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'url';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ import { config, getMeta, getTemplate, getTemplateSync, pgClients, getSelect, getSelectVal, getTemplatePath } from '@opengis/fastify-table/utils.js';
7
+
8
+ const { prefix = '/api' } = config;
9
+ const dirname = path.dirname(fileURLToPath(import.meta.url));
10
+
11
+ const maps = getTemplatePath('map')?.map?.(el => {
12
+ const { name = el[0] } = getTemplateSync('map', el[0]) || {};
13
+ return { slug: el[0], name };
14
+ });
15
+
16
+ async function processObject(loadTemplate, pg = pgClients.client, unittest) {
17
+ // default center for all maps (frontend dependends on it)
18
+ const { bbox = [], center = [30, 50] } = loadTemplate?.source_path && pg.pk?.[loadTemplate.source_path]
19
+ ? await pg.query(`select
20
+ array[ST_XMin(env), ST_YMin(env), ST_XMax(env),ST_YMax(env)] as bbox,
21
+ st_asgeojson(st_centroid(env))::json->'coordinates' as center
22
+ from ( select st_extent(geom) as env from ${loadTemplate.source_path} where ${loadTemplate.source_query || '1=1'})q`
23
+ ).then(el => el.rows?.[0] || {})
24
+ : {};
25
+ loadTemplate.map = { bbox, center };
26
+
27
+
28
+ if (!loadTemplate?.widgets?.length) return;
29
+ // add legend if not exists in widget
30
+ const idx = loadTemplate.widgets.findIndex(el => el.type === 'attribute_style');
31
+ const { source_path: attrTable, attribute, cls: clsName, legend = [], colors } = loadTemplate.widgets.find(el => el.type === 'attribute_style')?.config || {};
32
+ const colors1 = colors || ['red', 'black', 'blue', 'green', 'orange'];
33
+
34
+ if (!legend?.length && attribute && attrTable) {
35
+ const { columns = {} } = await getMeta({ pg, table: attrTable });
36
+ const { dataTypeID = 0 } = columns.find(item => item.name === attribute) || {};
37
+ const q = pg.pgType?.[dataTypeID]?.includes?.('[]')
38
+ ? `select unnest(${attribute})::text as id,count(*) from ${attrTable} group by unnest(${attribute}) limit 100`
39
+ : `select ${attribute}::text as id,count(*) from ${attrTable} group by ${attribute} limit 100`;
40
+
41
+ if (config.trace || unittest) console.log(q);
42
+ const countArr = await pg.queryCache(q, { time: 5 });
43
+
44
+ const ids = countArr.rows.map(item => item.id);
45
+
46
+ const cls = await getSelect(clsName, pg);
47
+ const clsData = await getSelectVal({ pg, values: ids, cls: clsName });
48
+
49
+ const options = countArr.rows.map((cel, idx) => {
50
+ const data = cls?.arr?.find?.(c => c.id?.toString?.() === cel.id?.toString?.()) || { text: clsData?.[cel.id]?.text || clsData?.[cel.id] };
51
+ const color = (colors?.length ? colors1[idx % colors1.length] : null) || data?.color || colors1[idx % colors1.length];
52
+ return { ...cel, ...data, color };
53
+ });
54
+ loadTemplate.widgets[idx].config.legend = options;
55
+ }
56
+
57
+
58
+ const { source_path: table, filters = [] } = loadTemplate.widgets.find(el => el.type === 'filters')?.config || {};
59
+
60
+ filters.forEach(el => Object.assign(el, { name: el.name || el.id }));
61
+
62
+ // md5 hash for suggest security
63
+ filters.filter(el => el.type?.toLowerCase() === 'select').map(async (el) => {
64
+ const hash = createHash('md5').update([table, el.name].join()).digest('hex');
65
+ el.api = `${prefix}/suggest/hash-${hash}`;
66
+ const filepath = path.join(dirname, `../../../../log/suggest/${hash}.json`);
67
+ if (existsSync(filepath)) { return; };
68
+ mkdirSync(path.dirname(filepath), { recursive: true });
69
+ writeFileSync(filepath, JSON.stringify({ table, column: el.name }), { encoding: 'utf8' });
70
+ });
71
+
72
+ // add options to filters
73
+ if (filters.filter(el => el.data).length && table) {
74
+ const { columns = {} } = await getMeta({ pg, table });
75
+ await Promise.all(filters.filter(el => el.data && el.name).map(async (el) => {
76
+ const { dataTypeID = 0 } = columns.find(item => item.name === el.name) || {};
77
+ const q = pg.pgType?.[dataTypeID]?.includes?.('[]')
78
+ ? `select unnest(${el.name})::text as id,count(*) from ${table} group by unnest(${el.name}) limit 100`
79
+ : `select ${el.name}::text as id,count(*) from ${table} group by ${el.name} limit 100`;
80
+
81
+ if (config.trace || unittest) console.log(q);
82
+ const countArr = await pg.queryCache(q, { time: 5 });
83
+
84
+ const ids = countArr.rows.map(item => item.id);
85
+
86
+ const cls = await getSelect(el.data, pg);
87
+ const clsData = await getSelectVal({ pg, values: ids, name: el.data });
88
+
89
+ const options = countArr.rows.map(cel => {
90
+ const data = cls?.arr?.find?.(c => c.id?.toString?.() === cel.id?.toString?.()) || { text: clsData[cel.id]?.text || clsData[cel.id] };
91
+ return { ...cel, ...data };
92
+ });
93
+ Object.assign(el, { options });
94
+ }));
95
+ }
96
+ return loadTemplate;
97
+ }
98
+
99
+ export default async function map({ pg = pgClients.client, params = {}, unittest }, reply) {
100
+ const { slug } = params;
101
+
102
+ const loadTemplate = await getTemplate('map', slug);
103
+
104
+ if (!loadTemplate) {
105
+ return reply.status(404).send('map not found');
106
+ }
107
+
108
+ if (!Array.isArray(loadTemplate)) {
109
+ await processObject(loadTemplate, pg, unittest);
110
+ return { ...loadTemplate, maps };
111
+ }
112
+
113
+ const index = loadTemplate?.find?.(el => el[0].split('.').shift() === 'index')?.[1];
114
+
115
+ if (!index) {
116
+ return reply.status(404).send('map index not found');
117
+ }
118
+
119
+ await processObject(index, pg, unittest);
120
+
121
+ const layers = loadTemplate?.filter?.(el => el[0].split('.').shift() !== 'index')?.map(el => ({ ...el[1], id: el[0].replace('.yml', '').replace('.json', '') }));
122
+
123
+ return reply.status(200).send({ ...index, layers, maps });
124
124
  }