@opengis/fastify-table
Version:
core-plugins
61 lines (47 loc) • 2.18 kB
JavaScript
import path from 'node:path';
import { config, logger, pgClients } from '../../../../utils.js';
import file2json from '../../../plugins/grpc/file2json.js';
export default async function file2geojson({ pg = pgClients.client, body = {} }, reply) {
const { file, srid, debug } = body;
if (!file || !srid) {
return reply.status(400).send('params file and srid are required');
}
const ext = path.extname(file);
if (!(['.zip', '.gdb', '.gpkg', '.geojson'].includes(ext))) {
return reply.status(400).send('Невірний формат файлів');
}
const filepath = path.join(config.folder || '', file);
try {
const JsonData = await file2json({ filepath, debug });
if (debug) return JsonData;
// if (JsonData?.features?.length > 1) return { error: 'too many features', status: 400 };
if (!JsonData?.features?.length && JsonData?.type?.toLowerCase() !== 'feature') {
return reply.status(400).send('invalid file content');
}
const JsonArr = JsonData?.features ? JsonData : { type: 'FeatureCollection', features: [JsonData] };
const { rows = [] } = await pg.query(`
select
features->>'type' as type,
features->'properties' as properties,
st_asgeojson(st_transform(st_setsrid(st_geomfromgeojson(features->>'geometry'),$2),4326))::json as geometry
from (
select d->>'type' as type,d->>'name' as name,json_array_elements(d->'features') as features
from (
select json_array_elements(case when json_typeof(d)='array' then d else json_build_array(d) end)d
from (
select ($1)::json as d
)q
)q
)q`, [JSON.stringify(JsonArr).replace(/'/g, '\'\''), srid]);
return reply.status(200).send([{ features: [rows.slice(0, 1)] }]);
}
catch (err) {
if (err?.detail?.includes('Infinity')) {
return { error: 'invalid geometry. Check input SRID', status: 400 };
}
logger.file('grpc/file2json', {
error: err.toString(), stack: err.stack, file, srid,
});
return reply.status(500).send(err.toString());
}
}