chat.controller.ts•1 kB
import { Controller, Post, Body, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { ChatService } from './chat.service';
@Controller('chat')
export class ChatController {
constructor(private chatService: ChatService) {}
@Post('message')
async sendMessage(
@Body() body: { message: string; conversationId?: string },
@Res() res: Response,
) {
const { message, conversationId } = body;
// 设置 SSE 响应头
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
try {
await this.chatService.processMessage(message, conversationId, (data) => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
});
res.write('data: [DONE]\n\n');
res.end();
} catch (error) {
res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`);
res.end();
}
}
}