@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
@@ -1,83 +1,83 @@
1
- import {
2
- pgClients, getTemplate, handlebars, metaFormat,
3
- } from '@opengis/fastify-table/utils.js';
4
-
5
- export default async function mapFormat(req, reply) {
6
- const { pg = pgClients.client, query = {} } = req;
7
- const { layer, id } = query;
8
- const time = Date.now();
9
-
10
- if (!layer || !id) return reply.status(404).send('not enough params: layer,id,map is required');
11
-
12
- const service = await getTemplate('layer', layer) || (pg.tlist.includes('gis.services') ? await pg.query('SELECT * FROM gis.services WHERE service_id = $1', [layer]).then(res => res.rows[0]) : null);
13
-
14
- const {
15
- source_path: tname, cardInterface, card, template,
16
- } = service;
17
-
18
- const columns = card;
19
- if (!tname) return reply.status(404).send('missing source_path');
20
-
21
- const pk = pg.pk?.[tname];
22
- if (!pk) return reply.status(404).send('missing pk');
23
-
24
- if (!columns) return reply.status(404).send('columns setting not found');
25
-
26
- const columnNames = columns.map(col => col.name);
27
- const excluded = ['created_by', 'created_at', 'updated_by', 'geom', 'id', 'uid', 'updated_at', 'cdate', 'editor_date', 'editor_id'];
28
- const filteredColumns = columnNames.filter(name => !excluded.includes(name));
29
-
30
- const rows = await pg.query(
31
- `SELECT ${pk} as "id", geom::json, ${filteredColumns.map(n => `"${n}"`).join(', ')} FROM ${tname} WHERE ${pk} = $1`,
32
- [id],
33
- ).then(el => el.rows || []);
34
-
35
- if (!rows.length) return reply.status(404).send('object not found');
36
-
37
- const classifiers = columns
38
- .filter(col => col.data && ['select', 'badge', 'tags'].includes(col.format))
39
- .reduce((acc, curr) => ({ ...acc, [curr.name]: curr.data }), {});
40
-
41
- await metaFormat({
42
- rows, table: tname, cls: classifiers, sufix: false,
43
- });
44
- const fullRow = rows[0];
45
-
46
- const result = [];
47
- const filtered = columns.filter(col => !excluded.includes(col.name));
48
- for (let i = 0; i < filtered.length; i += 1) {
49
- const col = filtered[i];
50
-
51
- const name = col.label || col.ua || col.name;
52
- const value = (col.format === 'date' ? new Date(fullRow[col.name]).toLocaleDateString('uk-UA') : null) || fullRow[`${col.name}_data`]?.text
53
- || fullRow[`${col.name}_text`]
54
- || fullRow[col.name];
55
-
56
- result.push(`<div class="grid grid-cols-1 gap-1 py-3 sm:grid-cols-3 sm:gap-4 even:bg-gray-50 text-[12px]">
57
- <dt class="text-gray-900">${name}</dt>
58
- <dd class="text-gray-700 sm:col-span-2">${value || '-'}</dd>
59
- </div>`);
60
- }
61
-
62
- const htmlTemplate = pg?.pk?.['admin.templates'] && service.card_mode === 'html'
63
- ? await pg.query('select body from admin.templates where name=$1 limit 1', [template || layer]).then(el => el.rows?.[0]?.body)
64
- : null;
65
-
66
- const html1 = htmlTemplate ? await handlebars.compile(htmlTemplate)(fullRow) : null;
67
-
68
- const html = html1 || `<dl class="divide-y divide-gray-100 py-[5px]">${result.join('')}</dl>`;
69
-
70
- const res = {
71
- time: Date.now() - time,
72
- id,
73
- rows: fullRow,
74
- columns,
75
- template,
76
- html,
77
- };
78
- if (service) {
79
- res.cardInterface = cardInterface;
80
- }
81
-
82
- return res;
83
- }
1
+ import {
2
+ pgClients, getTemplate, handlebars, metaFormat,
3
+ } from '@opengis/fastify-table/utils.js';
4
+
5
+ export default async function mapFormat(req, reply) {
6
+ const { pg = pgClients.client, query = {} } = req;
7
+ const { layer, id } = query;
8
+ const time = Date.now();
9
+
10
+ if (!layer || !id) return reply.status(404).send('not enough params: layer,id,map is required');
11
+
12
+ const service = await getTemplate('layer', layer) || (pg.tlist.includes('gis.services') ? await pg.query('SELECT * FROM gis.services WHERE service_id = $1', [layer]).then(res => res.rows[0]) : null);
13
+
14
+ const {
15
+ source_path: tname, cardInterface, card, template,
16
+ } = service;
17
+
18
+ const columns = card;
19
+ if (!tname) return reply.status(404).send('missing source_path');
20
+
21
+ const pk = pg.pk?.[tname];
22
+ if (!pk) return reply.status(404).send('missing pk');
23
+
24
+ if (!columns) return reply.status(404).send('columns setting not found');
25
+
26
+ const columnNames = columns.map(col => col.name);
27
+ const excluded = ['created_by', 'created_at', 'updated_by', 'geom', 'id', 'uid', 'updated_at', 'cdate', 'editor_date', 'editor_id'];
28
+ const filteredColumns = columnNames.filter(name => !excluded.includes(name));
29
+
30
+ const rows = await pg.query(
31
+ `SELECT ${pk} as "id", geom::json, ${filteredColumns.map(n => `"${n}"`).join(', ')} FROM ${tname} WHERE ${pk} = $1`,
32
+ [id],
33
+ ).then(el => el.rows || []);
34
+
35
+ if (!rows.length) return reply.status(404).send('object not found');
36
+
37
+ const classifiers = columns
38
+ .filter(col => col.data && ['select', 'badge', 'tags'].includes(col.format))
39
+ .reduce((acc, curr) => ({ ...acc, [curr.name]: curr.data }), {});
40
+
41
+ await metaFormat({
42
+ rows, table: tname, cls: classifiers, sufix: false,
43
+ });
44
+ const fullRow = rows[0];
45
+
46
+ const result = [];
47
+ const filtered = columns.filter(col => !excluded.includes(col.name));
48
+ for (let i = 0; i < filtered.length; i += 1) {
49
+ const col = filtered[i];
50
+
51
+ const name = col.label || col.ua || col.name;
52
+ const value = (col.format === 'date' ? new Date(fullRow[col.name]).toLocaleDateString('uk-UA') : null) || fullRow[`${col.name}_data`]?.text
53
+ || fullRow[`${col.name}_text`]
54
+ || fullRow[col.name];
55
+
56
+ result.push(`<div class="grid grid-cols-1 gap-1 py-3 sm:grid-cols-3 sm:gap-4 even:bg-gray-50 text-[12px]">
57
+ <dt class="text-gray-900">${name}</dt>
58
+ <dd class="text-gray-700 sm:col-span-2">${value || '-'}</dd>
59
+ </div>`);
60
+ }
61
+
62
+ const htmlTemplate = pg?.pk?.['admin.templates'] && service.card_mode === 'html'
63
+ ? await pg.query('select body from admin.templates where name=$1 limit 1', [template || layer]).then(el => el.rows?.[0]?.body)
64
+ : null;
65
+
66
+ const html1 = htmlTemplate ? await handlebars.compile(htmlTemplate)(fullRow) : null;
67
+
68
+ const html = html1 || `<dl class="divide-y divide-gray-100 py-[5px]">${result.join('')}</dl>`;
69
+
70
+ const res = {
71
+ time: Date.now() - time,
72
+ id,
73
+ rows: fullRow,
74
+ columns,
75
+ template,
76
+ html,
77
+ };
78
+ if (service) {
79
+ res.cardInterface = cardInterface;
80
+ }
81
+
82
+ return res;
83
+ }
@@ -1,153 +1,153 @@
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 } 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 mapTiles({ pg = pgClients.client, params = {}, query = {}, unittest }, reply) {
18
- const { slug, y, z } = params;
19
- const { sql, nocache, filter, pointZoom, type, layers, layer } = query;
20
- const x = params.x?.split?.('.')?.[0] - 0;
21
-
22
- if (!slug) {
23
- return reply.status(400).send('not enough params: slug');
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, layer].filter(Boolean).join();
39
-
40
- const filepath = path.join(
41
- rootFolder,
42
- `/map/vtile/${slug}/${hash ? `${createHash('md5').update(hash).digest('hex')}/` : ''}${z}/${x}/${y}.pbf`
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
- const loadTemplate = await getTemplate('map', slug);
55
-
56
- if (!loadTemplate) {
57
- return reply.status(404).send('map not found');
58
- }
59
-
60
- const index = loadTemplate?.find?.(el => el[0].split('.').shift() === 'index')?.[1];
61
-
62
- const layers1 = !index
63
- ? loadTemplate?.layers
64
- : loadTemplate?.filter?.(el => el[0].split('.').shift() !== 'index')?.map(el => ({ ...el[1], id: el[0].replace('.yml', '').replace('.json', '') }));
65
-
66
- if (!layers1?.length) {
67
- return reply.status(404).send('map layers not found');
68
- }
69
-
70
- layers1.forEach(el => Object.assign(el, { name: el.name || el.id }));
71
-
72
- const layers2 = layers1.filter(el => el.name && el.source_path).filter(el => layers ? layers.includes(el.name) : true).filter(el => layer ? el.name === layer : true);
73
-
74
- if (!layers2.length) {
75
- return reply.status(404).send('map layers sources not provided / invalid query params');
76
- }
77
-
78
- const allFilters = loadTemplate.widgets?.filter?.(el => el.type === 'filters') || [];
79
- const { filters: filterList = [], layer_id: layerId } = allFilters.find(el => layer ? el.config?.layer_id === layer : el.default)?.config || allFilters[0]?.config || {};
80
-
81
- const q = (await Promise.all(layers2.map(async (layer) => {
82
- const { source_path: source, id, name, style, geometry_type: gt, query: lquery, geometry_column: gCol } = layer;
83
- const loadTable = await getTemplate('table', source);
84
-
85
- const table = loadTable?.table || source;
86
- const meta = await getMeta({ pg, table });
87
- const { columns = [] } = meta || {};
88
- const geom = gCol || meta?.geom || 'geom';
89
- if (!columns?.length) return null;
90
-
91
- const pk = pg.pk?.[table] || loadTable?.key;
92
- const fData = filter && layerId === name ? await getFilterSQL({ pg, table: source, filterList, filter }) : {};
93
-
94
- const geomCol = parseInt(z, 10) < parseInt(pointZoom || '0', 10) || (style?.centroid && gt === 'point')
95
- ? `ST_Centroid(${geom})`
96
- : geom;
97
-
98
- const columnsFiltered = columns
99
- .filter(el => !['json', 'geometry'].includes(pg.pgType?.[el.dataTypeID]) && !systemColumns.includes(el.name));
100
-
101
- const props = columnsFiltered.map(el => {
102
- return el.type?.[0] === '_'
103
- ? `${el.name}[1] as ${el.name}`
104
- : `${el.name}${['int4'].includes(el.type) ? '::text' : ''}`;
105
- });
106
-
107
- return `SELECT ST_AsMVT(q, '${(id || name).replace(/'/g, "''")}', 4096, 'geom','row') as tile
108
- FROM (
109
- SELECT /*substr(${pk},12)::int*/ /*${(y - 0 + x) * 10000} + row_number() over()*/
110
-
111
- floor(random() * 100000 + 1)::int + row_number() over() as row,
112
-
113
- ${style?.colorAttr ? `${style.colorAttr},` : ''} ${props?.length ? `${props.map(el => `"${el}"`).join(',')},` : ''}
114
-
115
- ${pk} as id,
116
- ST_AsMVTGeom(st_transform(${geomCol},3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,true) geom
117
-
118
- FROM (select * from ${table} where ${loadTable?.query || '1=1'} and ${fData?.q || 'true'} and ${geom} && ${bbox2d}
119
-
120
- and ${geom} is not null and st_srid(${geom}) >0
121
-
122
- ${types[type] ? ` and ST_GeometryType(${geom}) = any ('{ ${types[type]} }') ` : ''}
123
-
124
- and ${lquery || '1=1'}
125
-
126
- ${gt === 'polygon' ? `order by st_area(st_transform(${geom},3857)) desc` : ''}
127
-
128
- limit ${limit})q
129
- ) q`;
130
- }))).filter(el => el).join(' union all ');
131
-
132
- if (sql === '1') return q;
133
- if (sql === '2') return filepath.replace(/\\/g, '/');
134
-
135
- const tile = await pg.query(q);
136
-
137
- if (unittest && !tile.rows?.length) {
138
- console.log(slug, q);
139
- }
140
-
141
- if (sql === '3') return tile.rows.map((el) => el.tile);
142
-
143
- if (sql === '4') return tile.rows.map((el) => el.tile);
144
-
145
- const buffer = Buffer.concat(tile.rows.map((el) => Buffer.from(el.tile)));
146
-
147
- if (!nocache) {
148
- await mkdir(path.dirname(filepath), { recursive: true });
149
- await writeFile(filepath, buffer, 'binary');
150
- }
151
-
152
- return reply.status(200).headers(headers).send(buffer);
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 } 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 mapTiles({ pg = pgClients.client, params = {}, query = {}, unittest }, reply) {
18
+ const { slug, y, z } = params;
19
+ const { sql, nocache, filter, pointZoom, type, layers, layer } = query;
20
+ const x = params.x?.split?.('.')?.[0] - 0;
21
+
22
+ if (!slug) {
23
+ return reply.status(400).send('not enough params: slug');
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, layer].filter(Boolean).join();
39
+
40
+ const filepath = path.join(
41
+ rootFolder,
42
+ `/map/vtile/${slug}/${hash ? `${createHash('md5').update(hash).digest('hex')}/` : ''}${z}/${x}/${y}.pbf`
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
+ const loadTemplate = await getTemplate('map', slug);
55
+
56
+ if (!loadTemplate) {
57
+ return reply.status(404).send('map not found');
58
+ }
59
+
60
+ const index = loadTemplate?.find?.(el => el[0].split('.').shift() === 'index')?.[1];
61
+
62
+ const layers1 = !index
63
+ ? loadTemplate?.layers
64
+ : loadTemplate?.filter?.(el => el[0].split('.').shift() !== 'index')?.map(el => ({ ...el[1], id: el[0].replace('.yml', '').replace('.json', '') }));
65
+
66
+ if (!layers1?.length) {
67
+ return reply.status(404).send('map layers not found');
68
+ }
69
+
70
+ layers1.forEach(el => Object.assign(el, { name: el.name || el.id }));
71
+
72
+ const layers2 = layers1.filter(el => el.name && el.source_path).filter(el => layers ? layers.includes(el.name) : true).filter(el => layer ? el.name === layer : true);
73
+
74
+ if (!layers2.length) {
75
+ return reply.status(404).send('map layers sources not provided / invalid query params');
76
+ }
77
+
78
+ const allFilters = loadTemplate.widgets?.filter?.(el => el.type === 'filters') || [];
79
+ const { filters: filterList = [], layer_id: layerId } = allFilters.find(el => layer ? el.config?.layer_id === layer : el.default)?.config || allFilters[0]?.config || {};
80
+
81
+ const q = (await Promise.all(layers2.map(async (layer) => {
82
+ const { source_path: source, id, name, style, geometry_type: gt, query: lquery, geometry_column: gCol } = layer;
83
+ const loadTable = await getTemplate('table', source);
84
+
85
+ const table = loadTable?.table || source;
86
+ const meta = await getMeta({ pg, table });
87
+ const { columns = [] } = meta || {};
88
+ const geom = gCol || meta?.geom || 'geom';
89
+ if (!columns?.length) return null;
90
+
91
+ const pk = pg.pk?.[table] || loadTable?.key;
92
+ const fData = filter && layerId === name ? await getFilterSQL({ pg, table: source, filterList, filter }) : {};
93
+
94
+ const geomCol = parseInt(z, 10) < parseInt(pointZoom || '0', 10) || (style?.centroid && gt === 'point')
95
+ ? `ST_Centroid(${geom})`
96
+ : geom;
97
+
98
+ const columnsFiltered = columns
99
+ .filter(el => !['json', 'geometry'].includes(pg.pgType?.[el.dataTypeID]) && !systemColumns.includes(el.name));
100
+
101
+ const props = columnsFiltered.map(el => {
102
+ return el.type?.[0] === '_'
103
+ ? `${el.name}[1] as ${el.name}`
104
+ : `${el.name}${['int4'].includes(el.type) ? '::text' : ''}`;
105
+ });
106
+
107
+ return `SELECT ST_AsMVT(q, '${(id || name).replace(/'/g, "''")}', 4096, 'geom','row') as tile
108
+ FROM (
109
+ SELECT /*substr(${pk},12)::int*/ /*${(y - 0 + x) * 10000} + row_number() over()*/
110
+
111
+ floor(random() * 100000 + 1)::int + row_number() over() as row,
112
+
113
+ ${style?.colorAttr ? `${style.colorAttr},` : ''} ${props?.length ? `${props.map(el => `"${el}"`).join(',')},` : ''}
114
+
115
+ ${pk} as id,
116
+ ST_AsMVTGeom(st_transform(${geomCol},3857),ST_TileEnvelope(${z},${y},${x})::box2d,4096,256,true) geom
117
+
118
+ FROM (select * from ${table} where ${loadTable?.query || '1=1'} and ${fData?.q || 'true'} and ${geom} && ${bbox2d}
119
+
120
+ and ${geom} is not null and st_srid(${geom}) >0
121
+
122
+ ${types[type] ? ` and ST_GeometryType(${geom}) = any ('{ ${types[type]} }') ` : ''}
123
+
124
+ and ${lquery || '1=1'}
125
+
126
+ ${gt === 'polygon' ? `order by st_area(st_transform(${geom},3857)) desc` : ''}
127
+
128
+ limit ${limit})q
129
+ ) q`;
130
+ }))).filter(el => el).join(' union all ');
131
+
132
+ if (sql === '1') return q;
133
+ if (sql === '2') return filepath.replace(/\\/g, '/');
134
+
135
+ const tile = await pg.query(q);
136
+
137
+ if (unittest && !tile.rows?.length) {
138
+ console.log(slug, q);
139
+ }
140
+
141
+ if (sql === '3') return tile.rows.map((el) => el.tile);
142
+
143
+ if (sql === '4') return tile.rows.map((el) => el.tile);
144
+
145
+ const buffer = Buffer.concat(tile.rows.map((el) => Buffer.from(el.tile)));
146
+
147
+ if (!nocache) {
148
+ await mkdir(path.dirname(filepath), { recursive: true });
149
+ await writeFile(filepath, buffer, 'binary');
150
+ }
151
+
152
+ return reply.status(200).headers(headers).send(buffer);
153
153
  }
@@ -1,16 +1,16 @@
1
- import { getTemplatePath, getTemplateSync } from "@opengis/fastify-table/utils.js";
2
-
3
- const arr = getTemplatePath('map') || [];
4
-
5
- const list = arr.map(el => {
6
- const { name = el[0] } = getTemplateSync('map', el[0]);
7
- return { name, slug: el[0] };
8
- });
9
-
10
- export default async function mapList(req, reply) {
11
- if (!arr.length) {
12
- return reply.status(200).send([]);
13
- }
14
-
15
- return reply.status(200).send(list);
1
+ import { getTemplatePath, getTemplateSync } from "@opengis/fastify-table/utils.js";
2
+
3
+ const arr = getTemplatePath('map') || [];
4
+
5
+ const list = arr.map(el => {
6
+ const { name = el[0] } = getTemplateSync('map', el[0]);
7
+ return { name, slug: el[0] };
8
+ });
9
+
10
+ export default async function mapList(req, reply) {
11
+ if (!arr.length) {
12
+ return reply.status(200).send([]);
13
+ }
14
+
15
+ return reply.status(200).send(list);
16
16
  }
@@ -1,43 +1,43 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'url';
4
-
5
- async function downloadImage(url, file) {
6
- const resp = await fetch(url);
7
- if (resp.status !== 200) throw new Error(`${url} - not found`);
8
- const blob = await resp.blob();
9
-
10
- const arrayBuffer = await blob.arrayBuffer();
11
-
12
- const buffer = Buffer.from(arrayBuffer);
13
-
14
- fs.writeFileSync(file, buffer);
15
- }
16
-
17
- const filename = fileURLToPath(import.meta.url);
18
- const dirname = path.dirname(filename);
19
-
20
- const fileIconDir = path.join(dirname, '../../../../log/marker-icon');
21
-
22
- fs.mkdirSync(fileIconDir, { recursive: true });
23
-
24
- export default async function markerIconApi(req, reply) {
25
- const { params = {} } = req;
26
- params.data = params['*'];
27
- if (!params.data) {
28
- return reply.status(400).send('not enough params: data');
29
- }
30
-
31
- const iconPath = path.join(fileIconDir, params?.data);
32
-
33
- if (fs.existsSync(iconPath)) {
34
- const buffer = fs.readFileSync(iconPath); // works for small files same as stream, but also unit-test-friendly
35
- return reply.type('image/png').send(buffer);
36
- }
37
-
38
- await downloadImage(`https://data.softpro.ua/api-user/marker/${params.data}`, iconPath).catch(err => {
39
- return reply.status(404).send('icon not found');
40
- });
41
- return fs.createReadStream(iconPath);
42
-
43
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ async function downloadImage(url, file) {
6
+ const resp = await fetch(url);
7
+ if (resp.status !== 200) throw new Error(`${url} - not found`);
8
+ const blob = await resp.blob();
9
+
10
+ const arrayBuffer = await blob.arrayBuffer();
11
+
12
+ const buffer = Buffer.from(arrayBuffer);
13
+
14
+ fs.writeFileSync(file, buffer);
15
+ }
16
+
17
+ const filename = fileURLToPath(import.meta.url);
18
+ const dirname = path.dirname(filename);
19
+
20
+ const fileIconDir = path.join(dirname, '../../../../log/marker-icon');
21
+
22
+ fs.mkdirSync(fileIconDir, { recursive: true });
23
+
24
+ export default async function markerIconApi(req, reply) {
25
+ const { params = {} } = req;
26
+ params.data = params['*'];
27
+ if (!params.data) {
28
+ return reply.status(400).send('not enough params: data');
29
+ }
30
+
31
+ const iconPath = path.join(fileIconDir, params?.data);
32
+
33
+ if (fs.existsSync(iconPath)) {
34
+ const buffer = fs.readFileSync(iconPath); // works for small files same as stream, but also unit-test-friendly
35
+ return reply.type('image/png').send(buffer);
36
+ }
37
+
38
+ await downloadImage(`https://data.softpro.ua/api-user/marker/${params.data}`, iconPath).catch(err => {
39
+ return reply.status(404).send('icon not found');
40
+ });
41
+ return fs.createReadStream(iconPath);
42
+
43
+ }