I create a method to upload data to a PostGIS database from an API using Node.js, this is the method:
app.get('/upload', async (req, res) => {
try {
const basePath = req.headers.path;
const fileName = basePath.match(/[^\\/]+$/);
const shpData = await shapefile.read(basePath);
const columnNames = Object.keys(shpData.features[0].properties);
const tableName = fileName[0].split('.')[0];
const tableExistsQuery = `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = '${tableName}')`;
const { rows } = await client.query(tableExistsQuery);
const tableExists = rows[0].exists;
if (!tableExists) {
const createTableQuery = `
CREATE TABLE ${tableName} (
gid SERIAL PRIMARY KEY,
geom GEOMETRY,
${columnNames.map(columnName => `${columnName} VARCHAR(255)`).join(', ')}
)
`;
await client.query(createTableQuery);
const uploadDataQuery = `ogr2ogr -f "PostgreSQL" PG:"dbname=${process.env.DATABASE} user=${process.env.USER} password=${process.env.PASSWORD} host=${process.env.HOST} port=${process.env.PORT}" ${basePath}.shp -nln ${tableName} -nlt PROMOTE_TO_MULTI`;
exec(uploadDataQuery, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
}
res.status(200).json({ message: 'Data uploaded in PostGIS database.' });
} catch (error) {
console.error('Error uploading data:', error);
res.status(500).json({ error: 'Error uploading data.' });
}
});
And the query is:
const uploadDataQuery = `ogr2ogr -f "PostgreSQL" PG:"dbname=${process.env.DATABASE} user=${process.env.USER} password=${process.env.PASSWORD} host=${process.env.HOST} port=${process.env.PORT}" ${basePath}.shp -nln ${tableName} -nlt PROMOTE_TO_MULTI`;
And it works only for a points shapefiles, but if I try to upload a poligon or line it fails: 2024-03-12 10:10:19 Error uploading data: RangeError: Offset is outside the bounds of the DataView 2024-03-12 10:10:19 at DataView.getUint8 () 2024-03-12 10:10:19 at new Dbf (/usr/src/app/node_modules/shapefile/dist/shapefile.node.js:80:20) 2024-03-12 10:10:19 at /usr/src/app/node_modules/shapefile/dist/shapefile.node.js:65:14 2024-03-12 10:10:19 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I tried with many types of shapefiles but I really don't know too much about PostGIS and Geoserver