50 lines
1.1 KiB
JavaScript
50 lines
1.1 KiB
JavaScript
const express = require('express');
|
|
const cors = require('cors');
|
|
const expressWs = require('express-ws');
|
|
const { listContainers, docker } = require('./docker');
|
|
|
|
const app = express();
|
|
const wsInstance = expressWs(app);
|
|
|
|
app.use(cors());
|
|
|
|
app.get('/api/services', async (req, res) => {
|
|
const services = await listContainers();
|
|
res.json(services);
|
|
});
|
|
|
|
app.ws('/api/events', (ws, req) => {
|
|
docker.getEvents((err, stream) => {
|
|
if (err) {
|
|
console.error(err);
|
|
ws.close();
|
|
return;
|
|
}
|
|
|
|
stream.on('data', (chunk) => {
|
|
const event = JSON.parse(chunk.toString());
|
|
if (event.Type === 'container' && (event.Action === 'start' || event.Action === 'stop')) {
|
|
ws.send(JSON.stringify({ type: 'container', action: event.Action }));
|
|
}
|
|
});
|
|
|
|
stream.on('end', () => {
|
|
ws.close();
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
stream.destroy();
|
|
});
|
|
});
|
|
});
|
|
|
|
app.get('/', (req, res) => {
|
|
res.send('Hello, World!');
|
|
});
|
|
|
|
const port = process.env.PORT || 3001;
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server listening on port ${port}`);
|
|
});
|