This repository was archived by the owner on Dec 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (69 loc) · 2.13 KB
/
server.js
File metadata and controls
91 lines (69 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env node
require('dotenv').config()
const express = require('express')
const cors = require('cors')
const w = require('./lib/utils/wrap')
const mongo = require('./lib/utils/mongo')
const db = require('./lib/models')
const app = express()
function badRequest(res, message) {
return res.status(400).send({
code: 400,
message
})
}
function toCleInterop(codeCommuneVoie, codeVoie, numero, suffixe) {
const paddedNumero = numero ? numero.padStart(5, '0') : null
return [codeCommuneVoie, codeVoie, paddedNumero, suffixe]
.filter(Boolean)
.join('_')
.toLowerCase()
}
app.use(cors({origin: true}))
app.get('/:codeCommune', w(async (req, res) => {
const {codeCommune} = req.params
const communeMetrics = await db.getCommuneMetrics(codeCommune)
if (!communeMetrics) {
return res.sendStatus(404)
}
res.send(communeMetrics)
}))
app.get('/:codeCommune/numeros', w(async (req, res) => {
if (!req.query.bbox) {
return badRequest(res, 'bbox is required')
}
const bbox = req.query.bbox.split(',').map(Number.parseFloat)
if (bbox.length !== 4 || bbox.some(Number.isNaN)) {
return badRequest(res, 'bbox is malformed')
}
const numeros = await db.getNumerosByBoundingBox(req.params.codeCommune, bbox)
res.send(numeros)
}))
app.get('/:codeCommuneVoie/:codeVoie', w(async (req, res) => {
const cleInterop = toCleInterop(req.params.codeCommuneVoie, req.params.codeVoie)
const voie = await db.getVoie(cleInterop)
if (!voie) {
return res.sendStatus(404)
}
res.send(voie)
}))
app.get('/:codeCommuneVoie/:codeVoie/:numeroComplet', w(async (req, res) => {
const [, numero, suffixe] = req.params.numeroComplet.match(/^(\d+)(\w*)$/)
const cleInterop = toCleInterop(req.params.codeCommuneVoie, req.params.codeVoie, numero, suffixe)
const adresse = await db.getNumero(cleInterop)
if (!adresse) {
return res.sendStatus(404)
}
res.send(adresse)
}))
const port = process.env.PORT || 5000
async function main() {
await mongo.connect()
app.listen(port, () => {
console.log('Start listening on port ' + port)
})
}
main().catch(error => {
console.error(error)
process.exit(1)
})