35 lines
971 B
JavaScript
35 lines
971 B
JavaScript
const http = require('http')
|
|
const express = require('express')
|
|
const cors = require('cors')
|
|
const { WebSocketServer } = require('ws')
|
|
const routes = require('./routes')
|
|
const { getSituation } = require('./situationData')
|
|
|
|
const app = express()
|
|
const PORT = process.env.API_PORT || 3001
|
|
|
|
app.use(cors())
|
|
app.use(express.json())
|
|
app.use('/api', routes)
|
|
app.get('/api/health', (_, res) => res.json({ ok: true }))
|
|
|
|
const server = http.createServer(app)
|
|
|
|
const wss = new WebSocketServer({ server, path: '/ws' })
|
|
wss.on('connection', (ws) => {
|
|
ws.send(JSON.stringify({ type: 'situation', data: getSituation() }))
|
|
})
|
|
function broadcastSituation() {
|
|
try {
|
|
const data = JSON.stringify({ type: 'situation', data: getSituation() })
|
|
wss.clients.forEach((c) => {
|
|
if (c.readyState === 1) c.send(data)
|
|
})
|
|
} catch (_) {}
|
|
}
|
|
setInterval(broadcastSituation, 5000)
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`API + WebSocket running at http://localhost:${PORT}`)
|
|
})
|