Add device id as source and redis connection management

This commit is contained in:
Apher 2026-06-29 01:19:23 +00:00
parent 05b99e21dc
commit 4c0d5b13d1

View File

@ -3,6 +3,7 @@ const db = models.db;
const redis = models.redis; const redis = models.redis;
const {sequelize, Sequelize} = db; const {sequelize, Sequelize} = db;
const Intent = db.intent; const Intent = db.intent;
const config = require("../config");
// Get all intents // Get all intents
exports.getAllIntents = async (req, res) => { exports.getAllIntents = async (req, res) => {
@ -31,21 +32,25 @@ exports.getIntentCommand = async (req, res) => {
console.log(`\n[FALLBACK API] Processing intent.`); console.log(`\n[FALLBACK API] Processing intent.`);
await redis.client.connect().catch(console.error)
const intents = await Intent.findAll(); const intents = await Intent.findAll();
const intent = intents.find(intent => intent.description === text); const intent = intents.find(intent => intent.description === text);
if (intent) { if (intent) {
const commandId = await redis.client.xAdd( const commandId = await redis.client.xAdd(
'commands', 'communication',
'*', '*',
{ {
device_id: device_id, device_id: device_id,
command: intent.command, command: intent.command,
processed_at: new Date().toISOString(), processed_at: new Date().toISOString(),
source: 'fallback_api', source: config.DEVICE_ID,
} }
); );
await redis.client.quit();
console.log(`Intent matched and published to stream: ${commandId}`); console.log(`Intent matched and published to stream: ${commandId}`);
return res.json({ return res.json({
@ -55,17 +60,19 @@ exports.getIntentCommand = async (req, res) => {
}); });
} else { } else {
const errorId = await redis.client.xAdd( const errorId = await redis.client.xAdd(
'commands', 'communication',
'*', '*',
{ {
device_id: device_id, device_id: device_id,
intent: 'error', intent: 'error',
command: 'intent_not_found', command: 'intent_not_found',
processed_at: new Date().toISOString(), processed_at: new Date().toISOString(),
source: 'fallback_api' source: config.DEVICE_ID
} }
); );
await redis.client.quit();
console.log(`No intent match, error published: ${errorId}`); console.log(`No intent match, error published: ${errorId}`);
return res.status(400).json({ return res.status(400).json({
@ -73,10 +80,12 @@ exports.getIntentCommand = async (req, res) => {
error: 'intent_not_found', error: 'intent_not_found',
message: `Could not understand: "${text}"`, message: `Could not understand: "${text}"`,
stream_id: errorId, stream_id: errorId,
source: 'fallback_api', source: config.DEVICE_ID,
}); });
} }
} catch (err) { } catch (err) {
await redis.client.quit();
console.error("getIntentCommand error:", err); console.error("getIntentCommand error:", err);
return res.status(500).send({message: err.message || "Internal server error."}); return res.status(500).send({message: err.message || "Internal server error."});