fix: add topic selection checkbox that auto-creates datapoints
When a user checks a topic checkbox, a datapoint is automatically created and the broker subscribes to that topic for live updates. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,9 @@ import {
|
||||
startDiscovery,
|
||||
addManualTopic,
|
||||
} from '../../modules/mqtt/topic-discovery';
|
||||
import { createDatapointFromMqtt, getDatapointByTopicId } from '../../modules/datapoints/datapoint-manager';
|
||||
import { getConnection } from './../../modules/mqtt/broker-manager';
|
||||
import { getDb } from '../../db/index';
|
||||
|
||||
const router = Router({ mergeParams: true });
|
||||
|
||||
@@ -21,8 +24,23 @@ router.get('/', (req, res): void => {
|
||||
// PUT /api/mqtt/brokers/:brokerId/topics/:id
|
||||
router.put('/:id', (req, res): void => {
|
||||
try {
|
||||
const topic = updateTopic(parseInt(req.params.id), req.body);
|
||||
if (!topic) { res.status(404).json({ error: 'Topic not found' }); return; }
|
||||
const topicId = parseInt(req.params.id);
|
||||
const topicRow = getDb().prepare('SELECT * FROM mqtt_topics WHERE id = ?').get(topicId) as any;
|
||||
if (!topicRow) { res.status(404).json({ error: 'Topic not found' }); return; }
|
||||
|
||||
const topic = updateTopic(topicId, req.body);
|
||||
|
||||
// If selecting a topic, auto-create a datapoint
|
||||
if (req.body.selected === 1 || req.body.selected === true) {
|
||||
const existing = getDatapointByTopicId(topicId);
|
||||
if (!existing) {
|
||||
createDatapointFromMqtt(topicRow.broker_id, topicId, topicRow.topic);
|
||||
}
|
||||
// Subscribe to the topic on the broker connection
|
||||
const client = getConnection(topicRow.broker_id);
|
||||
if (client?.connected) client.subscribe(topicRow.topic);
|
||||
}
|
||||
|
||||
res.json(topic);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
|
||||
Reference in New Issue
Block a user