@opengis/gis 0.2.9 → 0.2.11

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 (149) hide show
  1. package/README.md +5 -5
  2. package/dist/index.css +1 -1
  3. package/dist/index.js +3348 -3283
  4. package/dist/index.umd.cjs +36 -36
  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.group_list.form.json +17 -17
  42. package/module/gis/form/gis.maps.form.json +64 -64
  43. package/module/gis/form/gis.metadata.form.json +240 -240
  44. package/module/gis/form/gis.ogc_service.form.json +40 -40
  45. package/module/gis/form/gis.rasters.form.json +99 -99
  46. package/module/gis/form/gis.registers.form.json +110 -110
  47. package/module/gis/form/gis.registers_column.form.json +84 -84
  48. package/module/gis/form/gis.registers_filter.form.json +65 -65
  49. package/module/gis/form/gis.services.form.json +120 -120
  50. package/module/gis/form/gis.services_attributes.form.json +75 -75
  51. package/module/gis/form/gis.services_filter.form.json +65 -65
  52. package/module/gis/menu.json +43 -43
  53. package/module/gis/select/pg.columns.parent.sql +6 -6
  54. package/module/gis/select/pg.table_name.sql +17 -17
  55. package/module/gis/select/service_id.sql +1 -1
  56. package/module/gis/table/gis.group_list.table.json +35 -35
  57. package/module/gis/table/gis.maps.table.json +69 -69
  58. package/module/gis/table/gis.metadata.table.json +70 -70
  59. package/module/gis/table/gis.ogc_service.table.json +91 -91
  60. package/module/gis/table/gis.rasters.table.json +97 -97
  61. package/module/gis/table/gis.registers.table.json +79 -79
  62. package/module/gis/table/gis.services.table.json +99 -99
  63. package/module/gis/table/site.gis.registers.table.json +88 -88
  64. package/module/gis/table/site.gis.services.table.json +106 -106
  65. package/module/gis/templates/ISO19136_2017_gml_template.xml +330 -330
  66. package/module/gis/tokens.yml +5 -5
  67. package/module/test/cls/bp_build_type.json +37 -37
  68. package/module/test/cls/doc_status.json +31 -31
  69. package/module/test/cls/ts.temp_status.json +18 -18
  70. package/module/test/cls/ts.temp_structure.ts_class.json +49 -49
  71. package/module/test/cls/ts.temp_type.json +9 -9
  72. package/module/test/layer/bp.json +59 -59
  73. package/module/test/layer/bp1.yml +33 -33
  74. package/module/test/layer/individual.yml +53 -53
  75. package/module/test/layer/ts.linking_passport.yml +55 -55
  76. package/module/test/layer/ts.temp_structure.yml +50 -50
  77. package/module/test/map/addr.yml +21 -21
  78. package/module/test/map/bp_myo.json +43 -43
  79. package/module/test/map/bpf.json +43 -43
  80. package/module/test/map/main.json +36 -36
  81. package/module/test/map/mbd.json +91 -91
  82. package/module/test/map/ts.json +52 -52
  83. package/module/test/select/address_id.json +2 -2
  84. package/module/test/select/address_id.sql +7 -7
  85. package/module/test/select/core.user_uid.sql +1 -1
  86. package/module/test/table/data_address.street.table.json +69 -69
  87. package/module/test/table/data_bp_myo.bp.table.json +122 -122
  88. package/package.json +67 -67
  89. package/plugin.js +44 -43
  90. package/server/migrations/ogc.sql +106 -106
  91. package/server/migrations/rasters.sql +263 -263
  92. package/server/migrations/services.sql +247 -247
  93. package/server/migrations/widgets.sql +20 -20
  94. package/server/plugins/crons.js +21 -0
  95. package/server/plugins/mapnik/funcs/createXML.js +72 -72
  96. package/server/plugins/mapnik/funcs/gdalWrapper.js +72 -72
  97. package/server/plugins/mapnik/funcs/map.proto +241 -241
  98. package/server/plugins/mapnik/funcs/mapnik.js +106 -106
  99. package/server/plugins/mapnik/funcs/rasterConfig.js +11 -11
  100. package/server/plugins/mapnik/funcs/rasterExists.js +20 -20
  101. package/server/plugins/mapnik/funcs/rasterInfo.js +109 -109
  102. package/server/plugins/mapnik/funcs/rasterVrt.js +55 -55
  103. package/server/plugins/mapnik/funcs/rasterXML.js +65 -65
  104. package/server/plugins/mapnik/funcs/rootFolder.mjs +8 -8
  105. package/server/plugins/mapnik/utils/map.proto +241 -241
  106. package/server/plugins/vite.js +74 -74
  107. package/server/routes/gis/index.mjs +59 -59
  108. package/server/routes/gis/metadata/metadataXML.js +13 -13
  109. package/server/routes/gis/ogc/map.info.point.js +124 -124
  110. package/server/routes/gis/registers/add.registry.js +35 -35
  111. package/server/routes/gis/registers/del.registry.js +14 -14
  112. package/server/routes/gis/registers/funcs/classifiers.js +100 -100
  113. package/server/routes/gis/registers/funcs/columns.js +4 -4
  114. package/server/routes/gis/registers/funcs/content.type.js +9 -9
  115. package/server/routes/gis/registers/funcs/get.info.js +89 -89
  116. package/server/routes/gis/registers/funcs/handleRegistryRequest.js +122 -122
  117. package/server/routes/gis/registers/gis.export.js +148 -148
  118. package/server/routes/gis/registers/gis.registry.js +38 -38
  119. package/server/routes/gis/registers/gis.registry.list.js +59 -59
  120. package/server/routes/gis/registers/insert.columns.js +107 -107
  121. package/server/routes/gis/registers/insert.filters.js +110 -110
  122. package/server/routes/gis/registers/map.registry.js +79 -79
  123. package/server/routes/gis/services/add.service.js +64 -64
  124. package/server/routes/gis/services/del.service.js +12 -12
  125. package/server/routes/gis/services/get.layer.geom.js +27 -27
  126. package/server/routes/gis/services/get.services.col.js +33 -33
  127. package/server/routes/gis/services/get.services.js +84 -84
  128. package/server/routes/gis/services/legend.auto.js +77 -77
  129. package/server/routes/map/controllers/layerList.js +60 -60
  130. package/server/routes/map/controllers/map.js +123 -123
  131. package/server/routes/map/controllers/mapCatalog.js +72 -72
  132. package/server/routes/map/controllers/mapCatalogAttribute.js +55 -55
  133. package/server/routes/map/controllers/mapFeatures.js +128 -128
  134. package/server/routes/map/controllers/mapFormat.js +83 -83
  135. package/server/routes/map/controllers/mapTiles.js +152 -152
  136. package/server/routes/map/controllers/maps.js +15 -15
  137. package/server/routes/map/controllers/marker_icon.js +43 -43
  138. package/server/routes/map/controllers/rtile.js +134 -134
  139. package/server/routes/map/controllers/vtile.js +172 -166
  140. package/server/routes/map/index.mjs +86 -86
  141. package/server/routes/map/maps/add.map.js +41 -41
  142. package/server/routes/map/maps/del.map.js +18 -18
  143. package/server/routes/map/maps/get.map.js +88 -88
  144. package/server/routes/map/vtile1.js +170 -129
  145. package/server/routes/map/widgets/add.widget.js +38 -38
  146. package/server/routes/map/widgets/del.widget.js +22 -22
  147. package/server/routes/map/widgets/get.widget.js +40 -40
  148. package/server/routes/root.mjs +3 -3
  149. package/utils.js +11 -9
@@ -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,166 +1,172 @@
1
- import path from 'node:path';
2
- import { existsSync } from 'node:fs';
3
- import { createHash } from 'node:crypto';
4
- import { readFile, stat, mkdir, writeFile } from 'node:fs/promises';
5
-
6
- import Sphericalmercator from '@mapbox/sphericalmercator';
7
-
8
- import { getTemplate, pgClients, getFilterSQL, getMeta, yml2json, getColumnCLS, getSelect } from '@opengis/fastify-table/utils.js';
9
-
10
- import rootFolder from '../../../plugins/mapnik/funcs/rootFolder.mjs';
11
-
12
- const limit = 3000;
13
- const mercator = new Sphericalmercator({ size: 256 });
14
- const types = { point: 'ST_Point', polygon: 'ST_Polygon,ST_MultiPolygon' };
15
- const systemColumns = ['uid', 'cdate', 'editor_id', 'editor_date', 'created_by', 'created_at', 'updated_by', 'updated_at'];
16
-
17
- export default async function vtile({ pg = pgClients.client, params = {}, query = {}, unittest }, reply) {
18
- const { id, y, z } = params;
19
- const { sql, nocache, filter, pointZoom, type, layers } = query;
20
- const x = params.x?.split?.('.')?.[0] - 0;
21
-
22
- if (!id) {
23
- return reply.status(400).send('not enough params: id');
24
- }
25
-
26
- if (!x || !y || !z) {
27
- return reply.status(400).send('not enough params: xyz');
28
- }
29
-
30
- const bbox = mercator.bbox(+y, +x, +z, false);
31
- const bbox2d = `'BOX(${bbox[0]} ${bbox[1]},${bbox[2]} ${bbox[3]})'::box2d`;
32
-
33
- const headers = {
34
- 'Content-Type': 'application/x-protobuf',
35
- 'Cache-Control': nocache || sql ? 'no-cache' : 'public, max-age=86400',
36
- };
37
-
38
- const hash = [filter, layers].filter((el) => el).join();
39
-
40
- const filepath = path.join(
41
- rootFolder,
42
- `/map/vtile/${id}/${hash ? `${createHash('md5').update(hash).digest('hex')}/` : ''}${z}/${x}/${y}.vmt`
43
- );
44
-
45
- if (existsSync(filepath) && z < 13 && !nocache && !sql && !unittest) {
46
- const { birthtimeMs = Date.now() } = await stat(filepath);
47
- const ageInMs = Date.now() - birthtimeMs;
48
- if (ageInMs < 86400000) {
49
- const buffer = await readFile(filepath);
50
- return reply.status(200).headers(headers).send(buffer);
51
- }
52
- }
53
-
54
- if (!pg.pk?.['gis.services']) {
55
- return reply.status(404).send('services table not found');
56
- }
57
-
58
- const data = await pg.query(
59
- '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',
60
- [id]
61
- ).then(el => el.rows?.[0]);
62
-
63
- if (!data) {
64
- return reply.status(404).send('service not found');
65
- }
66
-
67
- const { source, gt, gc } = data;
68
-
69
- const style = data.style ? yml2json(data.style) : {};
70
-
71
- if (!source) {
72
- return reply.status(400).send('invalid service source path');
73
- }
74
-
75
- const loadTable = await getTemplate('table', source);
76
-
77
- const table = loadTable?.table || source;
78
-
79
- if (!pg.pk?.[table]?.length) {
80
- return reply.status(404).send('layer table not found');
81
- }
82
-
83
- const cls = getColumnCLS(table);
84
-
85
- const meta = await getMeta({ pg, table });
86
- const { columns = [] } = meta || {};
87
-
88
- const geom = gc || meta?.geom || 'geom';
89
- const pk = pg.pk?.[table] || loadTable?.key;
90
- const fData = filter ? await getFilterSQL({ pg, table: source, filter }) : {};
91
-
92
- const geomCol = parseInt(z, 10) < parseInt(pointZoom || '0', 10) || (style?.centroid && gt === 'point')
93
- ? `ST_Centroid(${geom})`
94
- : geom;
95
-
96
- const columnsFiltered = columns
97
- .filter(el => !['json', 'geometry'].includes(pg.pgType?.[el.dataTypeID]) && !systemColumns.includes(el.name));
98
-
99
- const props = columnsFiltered.map(el => {
100
- return el.type?.[0] === '_'
101
- ? `${el.name}[1] as ${el.name}`
102
- : `${el.name}${['int4'].includes(el.type) ? '::text' : ''}`;
103
- });
104
-
105
- const propsColumns = props.length ? await Promise.all(props.map(async colname => {
106
- if (!cls?.[colname]) return `"${colname}"`;
107
- const { type, data } = await pg.queryCache('select type, data from admin.cls where parent is null and name=$1 limit 1', { args: [cls[colname]], table: 'admin.cls' })
108
- .then(el => el.rows?.[0] || {}) || {};
109
-
110
- if (!type || type === 'sql' && !data) {
111
- return `"${colname}"`;
112
- }
113
-
114
- if (type === 'json') {
115
- return `(select name from admin.cls where parent='${cls[colname]}' and code="${colname}"::text) as "${colname}"`;
116
- }
117
-
118
- return `(with c(id,text) as (select * from (${data})q limit 1) select text from c where id::text="${colname}"::text) as "${colname}"`;
119
- })) : '';
120
-
121
- const q = `SELECT ST_AsMVT(q, '${id.replace(/'/g, "''")}', 4096, 'geom','row') as tile
122
- FROM (
123
- SELECT
124
-
125
- floor(random() * 100000 + 1)::int + row_number() over() as row,
126
-
127
- ${style?.colorAttr ? `${style.colorAttr},` : ''} ${propsColumns ? `${propsColumns.filter(Boolean).join('\n,') || ''},` : ''}
128
-
129
- ${pk} as id,
130
- ST_AsMVTGeom(st_transform(${style?.type === 'point' ? `st_pointonsurface(${geomCol})` : geomCol},3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,true) geom
131
-
132
- FROM (select * from ${table} where ${loadTable?.query || '1=1'} and ${fData?.q || 'true'} and ${geom} && ${bbox2d}
133
-
134
- and ${geom} is not null and st_srid(${geom}) >0
135
-
136
- ${types[type] ? ` and ST_GeometryType(${geom}) = any ('{ ${types[type]} }') ` : ''}
137
-
138
- and 1=1
139
-
140
- ${gt === 'polygon' ? `order by st_area(st_transform(${geom},3857)) desc` : ''}
141
-
142
- limit ${limit})q
143
- ) q`;
144
-
145
- if (sql === '1') return q;
146
- if (sql === '2') return filepath.replace(/\\/g, '/');
147
-
148
- const tile = await pg.query(q);
149
-
150
- if (unittest && !tile.rows?.length) {
151
- console.log(id, q);
152
- }
153
-
154
- if (sql === '3') return tile.rows.map((el) => el.tile);
155
-
156
- if (sql === '4') return tile.rows.map((el) => el.tile);
157
-
158
- const buffer = Buffer.concat(tile.rows.map((el) => Buffer.from(el.tile)));
159
-
160
- if (!nocache) {
161
- await mkdir(path.dirname(filepath), { recursive: true });
162
- await writeFile(filepath, buffer, 'binary');
163
- }
164
-
165
- return reply.status(200).headers(headers).send(buffer);
166
- }
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
+ }