|
1 | 1 | const express = require("express");
|
| 2 | +const Firestore = require("@google-cloud/firestore"); |
| 3 | + |
| 4 | +const db = new Firestore(); |
2 | 5 | const app = express();
|
| 6 | +app.use(express.json()); |
3 | 7 |
|
4 | 8 | app.get("/", (req, res) => {
|
5 | 9 | const name = process.env.NAME || "ESP32";
|
6 |
| - res.send(`Hello ${name}!`); |
| 10 | + res.send(`Welcome into ${name} Weather Station API!`); |
| 11 | +}); |
| 12 | + |
| 13 | +app.get("/weather/:placeId", async (req, res) => { |
| 14 | + const placeId = req.params.placeId; |
| 15 | + const query = db.collection("weather-data").where("placeId", "==", placeId); |
| 16 | + const querySnapshot = await query.get(); |
| 17 | + if (querySnapshot.size > 0) { |
| 18 | + res.json(querySnapshot.docs); |
| 19 | + } else { |
| 20 | + res.status(404).json({ status: `${placeID} not Found` }); |
| 21 | + } |
| 22 | +}); |
| 23 | + |
| 24 | +app.post("/weather", async (req, res) => { |
| 25 | + const data = { |
| 26 | + temperature: req.body.temperature, |
| 27 | + humidity: req.body.humidity, |
| 28 | + pressure: req.body.pressure, |
| 29 | + placeId: req.body.placeId, |
| 30 | + }; |
| 31 | + // .doc() creates a new document, .set() sets the data into it |
| 32 | + await db.collection("weather-data").doc().set(data); |
| 33 | + // res.status(200).json({ ...data }); |
| 34 | + res.statusCode(200); // to send only status code without any data |
7 | 35 | });
|
8 | 36 |
|
9 | 37 | const port = process.env.PORT || 8080;
|
|
0 commit comments