Merge branch 'dev' into main

This commit is contained in:
Alexis
2023-04-28 22:59:26 +02:00
3 changed files with 123 additions and 31 deletions

View File

@@ -1,71 +1,101 @@
const { createReadStream, readFileSync } = require('fs')
const { join } = require('path')
const express = require('express') const express = require('express')
const cors = require('cors') const cors = require('cors')
const morgan = require('morgan')
const helmet = require("helmet");
const json = require('big-json') const json = require('big-json')
const app = express()
app.use(cors())
const PORT = 3000
const fs = require('fs')
const path = require('path')
const GeoJsonGeometriesLookup = require("geojson-geometries-lookup") const GeoJsonGeometriesLookup = require("geojson-geometries-lookup")
const lookupTable = require('./rep-lookup') const lookupTable = require('./rep-lookup')
app.use(express.static(path.join(__dirname, 'public'))) const app = express()
const port = 3000
// Add modules to express app
app.use(cors())
app.use(morgan('common'))
app.use(helmet())
// Static files
app.use(express.static(join(__dirname, 'public')))
/**
* MAIN ROUTE
* Query params :
* latitude
* longitude
*/
app.use('/rep', async (req, res) => { app.use('/rep', async (req, res) => {
const lat = parseFloat(req.query.lat) let { lat, lon } = req.query
const lon = parseFloat(req.query.lon)
if (!lat || !lon) return // If the query doesn't contain the required params...
if (!lat || !lon) {
res.status(401).json({
"message": "The request is missing geolocation data. You must use 'lat' and 'lon' in your query."
});
return
}
const closestCity = await fetch( lat = parseFloat(lat)
lon = parseFloat(lon)
// Gets closest city from gov api to establish region data
const closestCity = await (await fetch(
`https://geo.api.gouv.fr/communes?lat=${lat}&lon=${lon}` `https://geo.api.gouv.fr/communes?lat=${lat}&lon=${lon}`
); )).json();
const body = await closestCity.json(); let codeDepartement = String(closestCity[0].codeDepartement)
let codeDepartement = String(body[0]?.codeDepartement)
if (!codeDepartement || codeDepartement === "") return // If somehow, the gov api can't find the nearest city...
if (!codeDepartement || codeDepartement === "") {
res.status(400).json({
"message": "The geolocation wasn't able to pinpoint the region the coords were in."
});
return
}
// Changes dep code to format of filenames on server, ie "075"
codeDepartement = codeDepartement.padStart(3, "0"); codeDepartement = codeDepartement.padStart(3, "0");
const pathToFeatures = path.join(__dirname, `public/cirs/${codeDepartement}.json`) // Gets the associated features with a read and parse stream
const readStream = fs.createReadStream(pathToFeatures) const pathToFeatures = join(__dirname, `public/cirs/${codeDepartement}.json`)
const readStream = createReadStream(pathToFeatures)
const parseStream = json.createParseStream() const parseStream = json.createParseStream()
parseStream.on('data', (pojo) => { parseStream.on('data', (pojo) => {
// Searches through all the geometries from the departement file data...
gl = new GeoJsonGeometriesLookup(pojo) gl = new GeoJsonGeometriesLookup(pojo)
const pos = { const pos = {
type: "Point", type: "Point",
coordinates: [lon, lat], coordinates: [lon, lat],
}; };
// Gets associated code for the country
const code = gl.getContainers(pos).features[0]?.properties["REF"] const code = gl.getContainers(pos).features[0]?.properties["REF"]
// If no code is found, send a 404
if (!code) { if (!code) {
res.json({ res.status(404).json({
"message": "The requested data couldn't be found. Maybe it was moved or the data isn't generated properly." "message": "The requested data couldn't be found. Maybe it was moved or the data isn't generated properly."
}).status(404).end(); });
return return
} }
const repFile = fs.readFileSync(path.join(__dirname, `public/reps/${lookupTable[code]}.json`), 'utf-8') // If a code is found, send the associated file containing the representant data
const repFile = readFileSync(join(__dirname, `public/reps/${lookupTable[code]}.json`), 'utf-8')
res.end(repFile) res.end(repFile)
}) })
readStream.pipe(parseStream); readStream.pipe(parseStream);
}) })
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`)); app.listen(port, () => console.log(`Server listening on port: ${port}`));
/** /**
* CUT DOWN CIRCO JSON * CUT DOWN CIRCO JSON
*/ */
// const f = fs.readFileSync(path.join(__dirname, 'public/circonscriptions-legislatives.json'), 'utf-8') // const f = fs.readFileSync(join(__dirname, 'public/circonscriptions-legislatives.json'), 'utf-8')
// const data = JSON.parse(f) // const data = JSON.parse(f)
// const features = Object.values(data.features) // const features = Object.values(data.features)
@@ -78,7 +108,7 @@ app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
// "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, // "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
// "features": value // "features": value
// } // }
// fs.writeFileSync(path.join(__dirname, `public/cirs/${key}.json`), JSON.stringify(output)) // fs.writeFileSync(join(__dirname, `public/cirs/${key}.json`), JSON.stringify(output))
// } // }
// function groupBy(list, keyGetter) { // function groupBy(list, keyGetter) {

62
package-lock.json generated
View File

@@ -9,7 +9,9 @@
"big-json": "^3.2.0", "big-json": "^3.2.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"geojson-geometries-lookup": "^0.5.0" "geojson-geometries-lookup": "^0.5.0",
"helmet": "^6.1.5",
"morgan": "^1.10.0"
} }
}, },
"node_modules/@turf/bbox": { "node_modules/@turf/bbox": {
@@ -118,6 +120,22 @@
"node": ">=0.8" "node": ">=0.8"
} }
}, },
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/basic-auth/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/big-json": { "node_modules/big-json": {
"version": "3.2.0", "version": "3.2.0",
"resolved": "https://registry.npmjs.org/big-json/-/big-json-3.2.0.tgz", "resolved": "https://registry.npmjs.org/big-json/-/big-json-3.2.0.tgz",
@@ -419,6 +437,14 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/helmet": {
"version": "6.1.5",
"resolved": "https://registry.npmjs.org/helmet/-/helmet-6.1.5.tgz",
"integrity": "sha512-UgAvdoG0BhF9vcCh/j0bWtElo2ZHHk6OzC98NLCM6zK03DEVSM0vUAtT7iR+oTo2Mi6sGelAH3tL6B/uUWxV4g==",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/http-errors": { "node_modules/http-errors": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -554,6 +580,32 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
"integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==",
"dependencies": {
"basic-auth": "~2.0.1",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-finished": "~2.3.0",
"on-headers": "~1.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/morgan/node_modules/on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@@ -594,6 +646,14 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": { "node_modules/once": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",

View File

@@ -6,7 +6,9 @@
"big-json": "^3.2.0", "big-json": "^3.2.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"geojson-geometries-lookup": "^0.5.0" "geojson-geometries-lookup": "^0.5.0",
"helmet": "^6.1.5",
"morgan": "^1.10.0"
}, },
"scripts": { "scripts": {
"start": "node index.js" "start": "node index.js"