Files
bigwo/test2/server/routes/session.js

118 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const router = express.Router();
const db = require('../db');
/**
* GET /api/session/list
* 获取会话列表(按更新时间倒序,带最后一条消息预览)
*/
router.get('/list', async (req, res) => {
try {
const userId = req.query.userId || null;
const limit = parseInt(req.query.limit) || 50;
const sessions = await db.getSessionList(userId, limit);
res.json({
success: true,
data: sessions.map((s) => ({
id: s.id,
userId: s.user_id,
mode: s.mode,
createdAt: s.created_at,
updatedAt: s.updated_at,
lastMessage: s.last_message ? (s.last_message.length > 60 ? s.last_message.slice(0, 60) + '...' : s.last_message) : null,
messageCount: parseInt(s.message_count) || 0,
})),
});
} catch (err) {
console.error('[Session] List failed:', err.message);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* DELETE /api/session/:id
* 删除会话及其所有消息
*/
router.delete('/:id', async (req, res) => {
try {
const { id } = req.params;
await db.deleteSession(id);
res.json({ success: true });
} catch (err) {
console.error('[Session] Delete failed:', err.message);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* GET /api/session/:id/history
* 获取会话完整历史(用于文字↔语音切换时加载上下文)
*/
router.get('/:id/history', async (req, res) => {
try {
const { id } = req.params;
const limit = parseInt(req.query.limit) || 20;
const format = req.query.format || 'llm'; // 'llm' | 'full'
let messages;
if (format === 'full') {
messages = await db.getRecentMessages(id, limit);
} else {
messages = await db.getHistoryForLLM(id, limit);
}
const session = await db.getSession(id);
res.json({
success: true,
data: {
sessionId: id,
mode: session?.mode || null,
messages,
count: messages.length,
},
});
} catch (err) {
console.error('[Session] Get history failed:', err.message);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* POST /api/session/:id/switch
* 切换会话模式voice ↔ chat返回上下文历史
*/
router.post('/:id/switch', async (req, res) => {
try {
const { id } = req.params;
const { targetMode } = req.body; // 'voice' | 'chat'
if (!targetMode || !['voice', 'chat'].includes(targetMode)) {
return res.status(400).json({ success: false, error: 'targetMode must be "voice" or "chat"' });
}
// 更新会话模式
await db.updateSessionMode(id, targetMode);
// 返回最近的对话历史供新模式使用
const history = await db.getHistoryForLLM(id, 20);
console.log(`[Session] Switched ${id} to ${targetMode}, history: ${history.length} messages`);
res.json({
success: true,
data: {
sessionId: id,
mode: targetMode,
history,
count: history.length,
},
});
} catch (err) {
console.error('[Session] Switch failed:', err.message);
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;