Initial commit
This commit is contained in:
80
test-backend/app.ts
Normal file
80
test-backend/app.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import express, { Express } from "express"
|
||||
import cors from "cors"
|
||||
import path from "path"
|
||||
import fs from "fs"
|
||||
import { fileURLToPath } from "url"
|
||||
import { dirname } from "path"
|
||||
import { MetersCollection, MeterFeature } from "shared-types/meters"
|
||||
|
||||
// ES module equivalent of __dirname
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = dirname(__filename)
|
||||
|
||||
const app: Express = express()
|
||||
const PORT = process.env.PORT || 3001
|
||||
|
||||
// Middleware
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
|
||||
// Route to serve the saudi_meters.json file
|
||||
app.get("/api/meters", (req, res) => {
|
||||
try {
|
||||
const filePath = path.join(__dirname, "saudi_meters.json")
|
||||
const data = fs.readFileSync(filePath, "utf8")
|
||||
const metersData: MetersCollection = JSON.parse(data)
|
||||
|
||||
res.json(metersData)
|
||||
} catch (error) {
|
||||
console.error("Error reading meters data:", error)
|
||||
res.status(500).json({ error: "Failed to load meters data" })
|
||||
}
|
||||
})
|
||||
|
||||
// Route to get individual meter by ID
|
||||
app.get("/api/meters/:id", (req, res) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const filePath = path.join(__dirname, "saudi_meters.json")
|
||||
const data = fs.readFileSync(filePath, "utf8")
|
||||
const metersData: MetersCollection = JSON.parse(data)
|
||||
|
||||
const meter = metersData.features.find(
|
||||
(feature: MeterFeature) => feature.properties.id === id
|
||||
)
|
||||
|
||||
if (meter) {
|
||||
res.json(meter)
|
||||
} else {
|
||||
res.status(404).json({ error: "Meter not found" })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error reading meters data:", error)
|
||||
res.status(500).json({ error: "Failed to load meters data" })
|
||||
}
|
||||
})
|
||||
|
||||
// Health check endpoint
|
||||
app.get("/health", (req, res) => {
|
||||
res.json({ status: "OK", timestamp: new Date().toISOString() })
|
||||
})
|
||||
|
||||
// Basic info endpoint
|
||||
app.get("/", (req, res) => {
|
||||
res.json({
|
||||
message: "Saudi Meters API Server",
|
||||
endpoints: {
|
||||
meters: "/api/meters",
|
||||
meterById: "/api/meters/:id",
|
||||
health: "/health",
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// Start the server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Server running on http://localhost:${PORT}`)
|
||||
console.log(`📊 Meters data available at http://localhost:${PORT}/api/meters`)
|
||||
})
|
||||
|
||||
export default app
|
||||
Reference in New Issue
Block a user