Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (57 loc) · 1.52 KB
/
Copy pathserver.js
File metadata and controls
71 lines (57 loc) · 1.52 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
const express = require("express")
const { MongoClient } = require("mongodb")
const cors = require("cors")
const app = express()
app.use(cors())
app.use(express.json())
// Connessione MongoDB (Docker)
const client = new MongoClient("mongodb://admin:password@localhost:27017")
let db
async function connectDB() {
await client.connect()
db = client.db("greenwheel")
console.log("✅ Connesso a MongoDB GreenWheel")
}
connectDB()
//prendi una corsa e la sua route
app.get("/route/:id", async (req, res) => {
try {
const rental = await db.collection("rentals").findOne({
rental_id: req.params.id
})
if (!rental) {
return res.status(404).json({ error: "Corsa non trovata" })
}
res.json(rental.route)
} catch (err) {
res.status(500).json({ error: "Errore server" })
}
})
// veicoli con batteria bassa
app.get("/low-battery", async (req, res) => {
const vehicles = await db.collection("vehicles")
.find({ battery: { $lt: 20 } })
.toArray()
res.json(vehicles)
})
//totale speso utente
app.get("/spent/:userId", async (req, res) => {
const result = await db.collection("rentals").aggregate([
{
$match: {
user_id: req.params.userId
}
},
{
$group: {
_id: "$user_id",
total_spent: { $sum: "$total_cost" }
}
}
]).toArray()
res.json(result)
})
//avvio server
app.listen(3000, () => {
console.log("Server GreenWheel attivo su http://localhost:3000")
})