@opengis/gis 0.2.26 → 0.2.28

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 (157) hide show
  1. package/README.md +5 -5
  2. package/dist/index.css +1 -1
  3. package/dist/index.js +4715 -4396
  4. package/dist/index.umd.cjs +55 -45
  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 +45 -45
  42. package/module/gis/form/gis.group_list.form.json +17 -17
  43. package/module/gis/form/gis.maps.form.json +61 -61
  44. package/module/gis/form/gis.metadata.form.json +240 -240
  45. package/module/gis/form/gis.ogc_service.form.json +45 -45
  46. package/module/gis/form/gis.rasters.form.json +103 -103
  47. package/module/gis/form/gis.registers.form.json +124 -124
  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 +111 -111
  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 +60 -60
  58. package/module/gis/table/gis.group_list.table.json +35 -35
  59. package/module/gis/table/gis.maps.table.json +99 -99
  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 +99 -99
  63. package/module/gis/table/gis.registers.table.json +142 -142
  64. package/module/gis/table/gis.services.table.json +118 -118
  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 +73 -73
  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/cartocss/add.cartocss.js +18 -18
  111. package/server/routes/gis/cartocss/get.cartocss.js +12 -12
  112. package/server/routes/gis/dashboard.js +29 -29
  113. package/server/routes/gis/index.mjs +73 -73
  114. package/server/routes/gis/metadata/metadataXML.js +13 -13
  115. package/server/routes/gis/ogc/map.info.point.js +124 -124
  116. package/server/routes/gis/registers/add.registry.js +35 -35
  117. package/server/routes/gis/registers/del.registry.js +14 -14
  118. package/server/routes/gis/registers/funcs/classifiers.js +100 -100
  119. package/server/routes/gis/registers/funcs/columns.js +4 -4
  120. package/server/routes/gis/registers/funcs/content.type.js +9 -9
  121. package/server/routes/gis/registers/funcs/get.info.js +89 -89
  122. package/server/routes/gis/registers/funcs/handleRegistryRequest.js +133 -133
  123. package/server/routes/gis/registers/gis.export.js +148 -148
  124. package/server/routes/gis/registers/gis.registry.js +70 -70
  125. package/server/routes/gis/registers/gis.registry.list.js +59 -59
  126. package/server/routes/gis/registers/insert.columns.js +107 -107
  127. package/server/routes/gis/registers/insert.filters.js +110 -110
  128. package/server/routes/gis/registers/map.registry.js +79 -79
  129. package/server/routes/gis/services/add.service.js +64 -64
  130. package/server/routes/gis/services/del.service.js +12 -12
  131. package/server/routes/gis/services/get.layer.geom.js +27 -27
  132. package/server/routes/gis/services/get.services.col.js +33 -33
  133. package/server/routes/gis/services/get.services.js +84 -84
  134. package/server/routes/gis/services/legend.auto.js +77 -77
  135. package/server/routes/map/controllers/geojson.js +187 -187
  136. package/server/routes/map/controllers/jsonData.js +205 -205
  137. package/server/routes/map/controllers/layerList.js +60 -60
  138. package/server/routes/map/controllers/map.js +123 -123
  139. package/server/routes/map/controllers/mapCatalog.js +72 -72
  140. package/server/routes/map/controllers/mapCatalogAttribute.js +55 -55
  141. package/server/routes/map/controllers/mapFeatures.js +128 -128
  142. package/server/routes/map/controllers/mapFormat.js +83 -83
  143. package/server/routes/map/controllers/mapTiles.js +152 -152
  144. package/server/routes/map/controllers/maps.js +15 -15
  145. package/server/routes/map/controllers/marker_icon.js +43 -43
  146. package/server/routes/map/controllers/rtile.js +134 -134
  147. package/server/routes/map/controllers/vtile.js +172 -172
  148. package/server/routes/map/index.mjs +142 -142
  149. package/server/routes/map/maps/add.map.js +41 -41
  150. package/server/routes/map/maps/del.map.js +18 -18
  151. package/server/routes/map/maps/get.map.js +86 -86
  152. package/server/routes/map/vtile1.js +170 -170
  153. package/server/routes/map/widgets/add.widget.js +38 -38
  154. package/server/routes/map/widgets/del.widget.js +22 -22
  155. package/server/routes/map/widgets/get.widget.js +40 -40
  156. package/server/routes/root.mjs +3 -3
  157. package/utils.js +11 -11
@@ -1,134 +1,134 @@
1
- import Sphericalmercator from '@mapbox/sphericalmercator';
2
- import path from 'node:path';
3
- import { existsSync } from 'node:fs';
4
- import { mkdir, writeFile, readFile } from 'node:fs/promises';
5
-
6
- import { config, logger, pgClients } from '@opengis/fastify-table/utils.js';
7
-
8
- import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
9
- import rasterXML from '../../../plugins/mapnik/funcs/rasterXML.js';
10
- import mapnik from '../../../plugins/mapnik/funcs/mapnik.js';
11
-
12
- const { render, loadXML } = mapnik();
13
-
14
- const mercator = new Sphericalmercator({ size: 256 });
15
-
16
- const loaded = {};
17
- const autoGenerate = {};
18
- /**
19
- * Формування растрового tile cartoCss
20
- *
21
- * @method GET
22
- * @alias rtile
23
- * @param {String} bbox - bbox
24
- * @param {Number} height - висота по координатам
25
- * @param {Number} width - ширина по координатам
26
- * @param {String} data - стилізація
27
- * @param {String} lang - мова
28
- * @param {String} z - координата z
29
- * @param {String} x - координата y
30
- * @param {String} y - координата x
31
- */
32
-
33
- export default async function rtile({
34
- pg = pgClients.client, params = {}, query = {}, user = {},
35
- }, reply) {
36
- if(!render) return reply.status(400).send('mapnik server address needed');
37
- const { id, z, y } = params;
38
- const { debug, nocache } = query;
39
- const db = pg.options?.database;
40
-
41
- const x = params.x.split('.')[0] - 0;
42
-
43
- if (!id) {
44
- return reply.status(400).send('not enough params: id');
45
- }
46
-
47
- if (!x || !y || !z) {
48
- return reply.status(400).send('not enough params: xyz');
49
- }
50
-
51
- const exists = pg.pk?.['gis.rasters']
52
- ? await pg.query('select raster_id from gis.rasters where raster_id=$1::text', [id])
53
- .then(el => el.rows?.[0]?.raster_id)
54
- : null;
55
-
56
- if (!exists) {
57
- return reply.status(404).send('raster not found');
58
- }
59
-
60
- const bbox = mercator.bbox(y, x, z, false, '900913');
61
- const styleXmlPath = path.join(rootFolder, 'mapnik', `${db}_${id}.xml`).replace(/\\/g, '/');
62
-
63
- if (debug === '1' && user?.uid) {
64
- return `python3 test/debug.py tmp/${id}.xml ${bbox.join(',')} /data/softpro/work/1.png`;
65
- }
66
-
67
- const filepath = path.join(
68
- rootFolder,
69
- `/rtile/${id}${z}/${x}/${y}.png`
70
- ).replace(/\\/g, '/');
71
-
72
- if (debug === '2' && user?.uid) {
73
- const sourcePath = await pg.query('SELECT source_path from gis.rasters where raster_id=$1', [id]).then(el => el.rows?.[0]?.source_path);
74
- const fullPath = sourcePath ? path.posix.join(config.mapServerRoot || '', config.folder, '/map/raster/', sourcePath, (sourcePath?.toLowerCase?.()?.includes?.('.tif') ? '' : 'mosaic.vrt')) : null;
75
- return { rootFolder, filepath, styleXmlPath, fullPath };
76
- }
77
-
78
- if (existsSync(filepath) && !nocache && !debug) {
79
- reply.headers({ 'Cache-Control': 'public, max-age=5184000', 'Content-Type': 'image/png', 'Cache-File': true });
80
- return readFile(filepath);
81
- }
82
-
83
- try {
84
- if (!autoGenerate[id] || debug === '3') {
85
- const resp = await rasterXML({ id, pg });
86
-
87
- if (resp?.error) {
88
- return reply.status(400).send(resp.error);
89
- }
90
-
91
- if (debug === '3' && user?.uid) {
92
- return resp;
93
- }
94
-
95
- autoGenerate[id] = 1;
96
- }
97
-
98
- if (!loaded[id] || debug === '4') {
99
- const xml = await readFile(styleXmlPath, 'utf-8');
100
-
101
- if (debug === '4' && user?.uid) {
102
- return xml;
103
- }
104
-
105
- await loadXML({ name: id, xml, reload: true });
106
- loaded[id] = 1;
107
- }
108
-
109
- const data = await render({
110
- name: id,
111
- width: 256,
112
- height: 256,
113
- bbox,
114
- });
115
-
116
- if (debug === '5' && user?.uid) {
117
- return { data, bbox, id, filepath };
118
- }
119
-
120
- if (data.err) {
121
- return data.err;
122
- }
123
-
124
- const buffer = Buffer.from(data.base64, 'base64');
125
-
126
- await mkdir(path.dirname(filepath), { recursive: true });
127
- await writeFile(filepath, buffer);
128
-
129
- return reply.headers({ 'Content-Type': 'image/png' }).send(buffer);
130
- } catch (err) {
131
- logger.file('rtile/error', { error: err.toString(), stack: err.stack });
132
- return reply.status(500).send('rtile error');
133
- }
134
- }
1
+ import Sphericalmercator from '@mapbox/sphericalmercator';
2
+ import path from 'node:path';
3
+ import { existsSync } from 'node:fs';
4
+ import { mkdir, writeFile, readFile } from 'node:fs/promises';
5
+
6
+ import { config, logger, pgClients } from '@opengis/fastify-table/utils.js';
7
+
8
+ import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
9
+ import rasterXML from '../../../plugins/mapnik/funcs/rasterXML.js';
10
+ import mapnik from '../../../plugins/mapnik/funcs/mapnik.js';
11
+
12
+ const { render, loadXML } = mapnik();
13
+
14
+ const mercator = new Sphericalmercator({ size: 256 });
15
+
16
+ const loaded = {};
17
+ const autoGenerate = {};
18
+ /**
19
+ * Формування растрового tile cartoCss
20
+ *
21
+ * @method GET
22
+ * @alias rtile
23
+ * @param {String} bbox - bbox
24
+ * @param {Number} height - висота по координатам
25
+ * @param {Number} width - ширина по координатам
26
+ * @param {String} data - стилізація
27
+ * @param {String} lang - мова
28
+ * @param {String} z - координата z
29
+ * @param {String} x - координата y
30
+ * @param {String} y - координата x
31
+ */
32
+
33
+ export default async function rtile({
34
+ pg = pgClients.client, params = {}, query = {}, user = {},
35
+ }, reply) {
36
+ if(!render) return reply.status(400).send('mapnik server address needed');
37
+ const { id, z, y } = params;
38
+ const { debug, nocache } = query;
39
+ const db = pg.options?.database;
40
+
41
+ const x = params.x.split('.')[0] - 0;
42
+
43
+ if (!id) {
44
+ return reply.status(400).send('not enough params: id');
45
+ }
46
+
47
+ if (!x || !y || !z) {
48
+ return reply.status(400).send('not enough params: xyz');
49
+ }
50
+
51
+ const exists = pg.pk?.['gis.rasters']
52
+ ? await pg.query('select raster_id from gis.rasters where raster_id=$1::text', [id])
53
+ .then(el => el.rows?.[0]?.raster_id)
54
+ : null;
55
+
56
+ if (!exists) {
57
+ return reply.status(404).send('raster not found');
58
+ }
59
+
60
+ const bbox = mercator.bbox(y, x, z, false, '900913');
61
+ const styleXmlPath = path.join(rootFolder, 'mapnik', `${db}_${id}.xml`).replace(/\\/g, '/');
62
+
63
+ if (debug === '1' && user?.uid) {
64
+ return `python3 test/debug.py tmp/${id}.xml ${bbox.join(',')} /data/softpro/work/1.png`;
65
+ }
66
+
67
+ const filepath = path.join(
68
+ rootFolder,
69
+ `/rtile/${id}${z}/${x}/${y}.png`
70
+ ).replace(/\\/g, '/');
71
+
72
+ if (debug === '2' && user?.uid) {
73
+ const sourcePath = await pg.query('SELECT source_path from gis.rasters where raster_id=$1', [id]).then(el => el.rows?.[0]?.source_path);
74
+ const fullPath = sourcePath ? path.posix.join(config.mapServerRoot || '', config.folder, '/map/raster/', sourcePath, (sourcePath?.toLowerCase?.()?.includes?.('.tif') ? '' : 'mosaic.vrt')) : null;
75
+ return { rootFolder, filepath, styleXmlPath, fullPath };
76
+ }
77
+
78
+ if (existsSync(filepath) && !nocache && !debug) {
79
+ reply.headers({ 'Cache-Control': 'public, max-age=5184000', 'Content-Type': 'image/png', 'Cache-File': true });
80
+ return readFile(filepath);
81
+ }
82
+
83
+ try {
84
+ if (!autoGenerate[id] || debug === '3') {
85
+ const resp = await rasterXML({ id, pg });
86
+
87
+ if (resp?.error) {
88
+ return reply.status(400).send(resp.error);
89
+ }
90
+
91
+ if (debug === '3' && user?.uid) {
92
+ return resp;
93
+ }
94
+
95
+ autoGenerate[id] = 1;
96
+ }
97
+
98
+ if (!loaded[id] || debug === '4') {
99
+ const xml = await readFile(styleXmlPath, 'utf-8');
100
+
101
+ if (debug === '4' && user?.uid) {
102
+ return xml;
103
+ }
104
+
105
+ await loadXML({ name: id, xml, reload: true });
106
+ loaded[id] = 1;
107
+ }
108
+
109
+ const data = await render({
110
+ name: id,
111
+ width: 256,
112
+ height: 256,
113
+ bbox,
114
+ });
115
+
116
+ if (debug === '5' && user?.uid) {
117
+ return { data, bbox, id, filepath };
118
+ }
119
+
120
+ if (data.err) {
121
+ return data.err;
122
+ }
123
+
124
+ const buffer = Buffer.from(data.base64, 'base64');
125
+
126
+ await mkdir(path.dirname(filepath), { recursive: true });
127
+ await writeFile(filepath, buffer);
128
+
129
+ return reply.headers({ 'Content-Type': 'image/png' }).send(buffer);
130
+ } catch (err) {
131
+ logger.file('rtile/error', { error: err.toString(), stack: err.stack });
132
+ return reply.status(500).send('rtile error');
133
+ }
134
+ }
@@ -1,172 +1,172 @@
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 Sphericalmercator from '@mapbox/sphericalmercator';
9
-
10
- import {
11
- getTemplate, pgClients, getFilterSQL, getMeta, yml2json, getColumnCLS, getSelect,
12
- } from '@opengis/fastify-table/utils.js';
13
-
14
- import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
15
-
16
- const limit = 3000;
17
- const mercator = new Sphericalmercator({ size: 256 });
18
- const types = { point: 'ST_Point', polygon: 'ST_Polygon,ST_MultiPolygon' };
19
- const systemColumns = ['uid', 'cdate', 'editor_id', 'editor_date', 'created_by', 'created_at', 'updated_by', 'updated_at'];
20
-
21
- export default async function vtile({
22
- pg = pgClients.client, params = {}, query = {}, unittest,
23
- }, reply) {
24
- const { id, y, z } = params;
25
- const {
26
- sql, nocache, filter, pointZoom, type, layers,
27
- } = query;
28
- const x = params.x?.split?.('.')?.[0] - 0;
29
-
30
- if (!id) {
31
- return reply.status(400).send('not enough params: id');
32
- }
33
-
34
- if (!x || !y || !z) {
35
- return reply.status(400).send('not enough params: xyz');
36
- }
37
-
38
- const bbox = mercator.bbox(+y, +x, +z, false);
39
- const bbox2d = `'BOX(${bbox[0]} ${bbox[1]},${bbox[2]} ${bbox[3]})'::box2d`;
40
-
41
- const headers = {
42
- 'Content-Type': 'application/x-protobuf',
43
- 'Cache-Control': nocache || sql ? 'no-cache' : 'public, max-age=86400',
44
- };
45
-
46
- const hash = [filter, layers].filter((el) => el).join();
47
-
48
- const filepath = path.join(
49
- rootFolder,
50
- `/vtile/${id}/${hash ? `${createHash('md5').update(hash).digest('hex')}/` : ''}${z}/${x}/${y}.vmt`,
51
- );
52
-
53
- if (existsSync(filepath) && z < 13 && !nocache && !sql && !unittest) {
54
- const { birthtimeMs = Date.now() } = await stat(filepath);
55
- const ageInMs = Date.now() - birthtimeMs;
56
- if (ageInMs < 86400000) {
57
- const buffer = await readFile(filepath);
58
- return reply.status(200).headers(headers).send(buffer);
59
- }
60
- }
61
-
62
- if (!pg.pk?.['gis.services']) {
63
- return reply.status(404).send('services table not found');
64
- }
65
-
66
- const data = await pg.query(
67
- 'select source_path as source, style, geom_type as gt, geometry_column as gc from gis.services where service_id=$1 and is_active and is_public',
68
- [id],
69
- ).then(el => el.rows?.[0]);
70
-
71
- if (!data) {
72
- return reply.status(404).send('service not found');
73
- }
74
-
75
- const { source, gt, gc } = data;
76
-
77
- const style = data.style ? yml2json(data.style) : {};
78
-
79
- if (!source) {
80
- return reply.status(400).send('invalid service source path');
81
- }
82
-
83
- const loadTable = await getTemplate('table', source);
84
-
85
- const table = loadTable?.table || source;
86
-
87
- if (!pg.pk?.[table]?.length) {
88
- return reply.status(404).send('layer table not found');
89
- }
90
-
91
- const cls = getColumnCLS(table);
92
-
93
- const meta = await getMeta({ pg, table });
94
- const { columns = [] } = meta || {};
95
-
96
- const geom = gc || meta?.geom || 'geom';
97
- const pk = pg.pk?.[table] || loadTable?.key;
98
- const fData = filter ? await getFilterSQL({ pg, table: source, filter }) : {};
99
-
100
- const geomCol = parseInt(z, 10) < parseInt(pointZoom || '0', 10) || (style?.centroid && gt === 'point')
101
- ? `ST_Centroid(${geom})`
102
- : geom;
103
-
104
- const columnsFiltered = columns
105
- .filter(el => !['json', 'geometry'].includes(pg.pgType?.[el.dataTypeID]) && !systemColumns.includes(el.name));
106
-
107
- const props = columnsFiltered.map(el => (el.type?.[0] === '_'
108
- ? `${el.name}[1] as ${el.name}`
109
- : `${el.name}${['int4'].includes(el.type) ? '::text' : ''}`));
110
-
111
- const propsColumns = props.length ? await Promise.all(props.map(async colname => {
112
- if (!cls?.[colname]) return `"${colname}"`;
113
- const { type: type2, data: data2 } = await pg.queryCache('select type, data from admin.cls where parent is null and name=$1 limit 1', { args: [cls[colname]], table: 'admin.cls' })
114
- .then(el => el.rows?.[0] || {}) || {};
115
-
116
- if (!type2 || (type2 === 'sql' && !data2)) {
117
- return `"${colname}"`;
118
- }
119
-
120
- if (type2 === 'json') {
121
- return `(select name from admin.cls where parent='${cls[colname]}' and code="${colname}"::text) as "${colname}"`;
122
- }
123
-
124
- return `(with c(id,text) as (select * from (${data2})q limit 1) select text from c where id::text="${colname}"::text) as "${colname}"`;
125
- })) : '';
126
-
127
- const q = `SELECT ST_AsMVT(q, '${id.replace(/'/g, "''")}', 4096, 'geom','row') as tile
128
- FROM (
129
- SELECT
130
-
131
- floor(random() * 100000 + 1)::int + row_number() over() as row,
132
-
133
- ${style?.colorAttr ? `${style.colorAttr},` : ''} ${propsColumns ? `${propsColumns.filter(Boolean).join('\n,') || ''},` : ''}
134
-
135
- ${pk} as id,
136
- ST_AsMVTGeom(st_transform(${style?.type === 'point' ? `st_pointonsurface(${geomCol})` : geomCol},3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,true) geom
137
-
138
- FROM (select * from ${table} where ${loadTable?.query || '1=1'} and ${fData?.q || 'true'} and ${geom} && ${bbox2d}
139
-
140
- and ${geom} is not null and st_srid(${geom}) >0
141
-
142
- ${types[type] ? ` and ST_GeometryType(${geom}) = any ('{ ${types[type]} }') ` : ''}
143
-
144
- and 1=1
145
-
146
- ${gt === 'polygon' ? `order by st_area(st_transform(${geom},3857)) desc` : ''}
147
-
148
- limit ${limit})q
149
- ) q`;
150
-
151
- if (sql === '1') return q;
152
- if (sql === '2') return filepath.replace(/\\/g, '/');
153
-
154
- const tile = await pg.query(q);
155
-
156
- if (unittest && !tile.rows?.length) {
157
- console.log(id, q);
158
- }
159
-
160
- if (sql === '3') return tile.rows.map((el) => el.tile);
161
-
162
- if (sql === '4') return tile.rows.map((el) => el.tile);
163
-
164
- const buffer = Buffer.concat(tile.rows.map((el) => Buffer.from(el.tile)));
165
-
166
- if (!nocache) {
167
- await mkdir(path.dirname(filepath), { recursive: true });
168
- await writeFile(filepath, buffer, 'binary');
169
- }
170
-
171
- return reply.status(200).headers(headers).send(buffer);
172
- }
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 Sphericalmercator from '@mapbox/sphericalmercator';
9
+
10
+ import {
11
+ getTemplate, pgClients, getFilterSQL, getMeta, yml2json, getColumnCLS, getSelect,
12
+ } from '@opengis/fastify-table/utils.js';
13
+
14
+ import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
15
+
16
+ const limit = 3000;
17
+ const mercator = new Sphericalmercator({ size: 256 });
18
+ const types = { point: 'ST_Point', polygon: 'ST_Polygon,ST_MultiPolygon' };
19
+ const systemColumns = ['uid', 'cdate', 'editor_id', 'editor_date', 'created_by', 'created_at', 'updated_by', 'updated_at'];
20
+
21
+ export default async function vtile({
22
+ pg = pgClients.client, params = {}, query = {}, unittest,
23
+ }, reply) {
24
+ const { id, y, z } = params;
25
+ const {
26
+ sql, nocache, filter, pointZoom, type, layers,
27
+ } = query;
28
+ const x = params.x?.split?.('.')?.[0] - 0;
29
+
30
+ if (!id) {
31
+ return reply.status(400).send('not enough params: id');
32
+ }
33
+
34
+ if (!x || !y || !z) {
35
+ return reply.status(400).send('not enough params: xyz');
36
+ }
37
+
38
+ const bbox = mercator.bbox(+y, +x, +z, false);
39
+ const bbox2d = `'BOX(${bbox[0]} ${bbox[1]},${bbox[2]} ${bbox[3]})'::box2d`;
40
+
41
+ const headers = {
42
+ 'Content-Type': 'application/x-protobuf',
43
+ 'Cache-Control': nocache || sql ? 'no-cache' : 'public, max-age=86400',
44
+ };
45
+
46
+ const hash = [filter, layers].filter((el) => el).join();
47
+
48
+ const filepath = path.join(
49
+ rootFolder,
50
+ `/vtile/${id}/${hash ? `${createHash('md5').update(hash).digest('hex')}/` : ''}${z}/${x}/${y}.vmt`,
51
+ );
52
+
53
+ if (existsSync(filepath) && z < 13 && !nocache && !sql && !unittest) {
54
+ const { birthtimeMs = Date.now() } = await stat(filepath);
55
+ const ageInMs = Date.now() - birthtimeMs;
56
+ if (ageInMs < 86400000) {
57
+ const buffer = await readFile(filepath);
58
+ return reply.status(200).headers(headers).send(buffer);
59
+ }
60
+ }
61
+
62
+ if (!pg.pk?.['gis.services']) {
63
+ return reply.status(404).send('services table not found');
64
+ }
65
+
66
+ const data = await pg.query(
67
+ 'select source_path as source, style, geom_type as gt, geometry_column as gc from gis.services where service_id=$1 and is_active and is_public',
68
+ [id],
69
+ ).then(el => el.rows?.[0]);
70
+
71
+ if (!data) {
72
+ return reply.status(404).send('service not found');
73
+ }
74
+
75
+ const { source, gt, gc } = data;
76
+
77
+ const style = data.style ? yml2json(data.style) : {};
78
+
79
+ if (!source) {
80
+ return reply.status(400).send('invalid service source path');
81
+ }
82
+
83
+ const loadTable = await getTemplate('table', source);
84
+
85
+ const table = loadTable?.table || source;
86
+
87
+ if (!pg.pk?.[table]?.length) {
88
+ return reply.status(404).send('layer table not found');
89
+ }
90
+
91
+ const cls = getColumnCLS(table);
92
+
93
+ const meta = await getMeta({ pg, table });
94
+ const { columns = [] } = meta || {};
95
+
96
+ const geom = gc || meta?.geom || 'geom';
97
+ const pk = pg.pk?.[table] || loadTable?.key;
98
+ const fData = filter ? await getFilterSQL({ pg, table: source, filter }) : {};
99
+
100
+ const geomCol = parseInt(z, 10) < parseInt(pointZoom || '0', 10) || (style?.centroid && gt === 'point')
101
+ ? `ST_Centroid(${geom})`
102
+ : geom;
103
+
104
+ const columnsFiltered = columns
105
+ .filter(el => !['json', 'geometry'].includes(pg.pgType?.[el.dataTypeID]) && !systemColumns.includes(el.name));
106
+
107
+ const props = columnsFiltered.map(el => (el.type?.[0] === '_'
108
+ ? `${el.name}[1] as ${el.name}`
109
+ : `${el.name}${['int4'].includes(el.type) ? '::text' : ''}`));
110
+
111
+ const propsColumns = props.length ? await Promise.all(props.map(async colname => {
112
+ if (!cls?.[colname]) return `"${colname}"`;
113
+ const { type: type2, data: data2 } = await pg.queryCache('select type, data from admin.cls where parent is null and name=$1 limit 1', { args: [cls[colname]], table: 'admin.cls' })
114
+ .then(el => el.rows?.[0] || {}) || {};
115
+
116
+ if (!type2 || (type2 === 'sql' && !data2)) {
117
+ return `"${colname}"`;
118
+ }
119
+
120
+ if (type2 === 'json') {
121
+ return `(select name from admin.cls where parent='${cls[colname]}' and code="${colname}"::text) as "${colname}"`;
122
+ }
123
+
124
+ return `(with c(id,text) as (select * from (${data2})q limit 1) select text from c where id::text="${colname}"::text) as "${colname}"`;
125
+ })) : '';
126
+
127
+ const q = `SELECT ST_AsMVT(q, '${id.replace(/'/g, "''")}', 4096, 'geom','row') as tile
128
+ FROM (
129
+ SELECT
130
+
131
+ floor(random() * 100000 + 1)::int + row_number() over() as row,
132
+
133
+ ${style?.colorAttr ? `${style.colorAttr},` : ''} ${propsColumns ? `${propsColumns.filter(Boolean).join('\n,') || ''},` : ''}
134
+
135
+ ${pk} as id,
136
+ ST_AsMVTGeom(st_transform(${style?.type === 'point' ? `st_pointonsurface(${geomCol})` : geomCol},3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,true) geom
137
+
138
+ FROM (select * from ${table} where ${loadTable?.query || '1=1'} and ${fData?.q || 'true'} and ${geom} && ${bbox2d}
139
+
140
+ and ${geom} is not null and st_srid(${geom}) >0
141
+
142
+ ${types[type] ? ` and ST_GeometryType(${geom}) = any ('{ ${types[type]} }') ` : ''}
143
+
144
+ and 1=1
145
+
146
+ ${gt === 'polygon' ? `order by st_area(st_transform(${geom},3857)) desc` : ''}
147
+
148
+ limit ${limit})q
149
+ ) q`;
150
+
151
+ if (sql === '1') return q;
152
+ if (sql === '2') return filepath.replace(/\\/g, '/');
153
+
154
+ const tile = await pg.query(q);
155
+
156
+ if (unittest && !tile.rows?.length) {
157
+ console.log(id, q);
158
+ }
159
+
160
+ if (sql === '3') return tile.rows.map((el) => el.tile);
161
+
162
+ if (sql === '4') return tile.rows.map((el) => el.tile);
163
+
164
+ const buffer = Buffer.concat(tile.rows.map((el) => Buffer.from(el.tile)));
165
+
166
+ if (!nocache) {
167
+ await mkdir(path.dirname(filepath), { recursive: true });
168
+ await writeFile(filepath, buffer, 'binary');
169
+ }
170
+
171
+ return reply.status(200).headers(headers).send(buffer);
172
+ }