Files
heala-backend/src/modules/chatbot/chatbot.controller.ts
T

60 lines
1.3 KiB
TypeScript

import {
Body,
Controller,
HttpCode,
HttpStatus,
Post,
Res,
} from '@nestjs/common';
import { ChatbotService } from './providers/chatbot.service';
import type { Response } from 'express';
import { ChatDTO } from './dtos/chat.dto';
import { ActiveUser } from '@/common/decorators/active-user.decorator';
import { User } from '../users/entities/user.entity';
@Controller('chatbot')
export class ChatbotController {
constructor(
/**
* Inject Chatbot Service
*/
private readonly chatbotService: ChatbotService,
) {}
@Post('chat')
@HttpCode(HttpStatus.OK)
public async chat(@Body() chatDto: ChatDTO, @ActiveUser() user: User) {
return this.chatbotService.chat(
user,
chatDto.message,
chatDto.conversationId,
);
}
@Post('stream')
@HttpCode(HttpStatus.OK)
public async streamChat(
@Body() chatDto: ChatDTO,
@ActiveUser() user: User,
@Res() res: Response,
) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
for await (const content of this.chatbotService.streamChat(
user,
chatDto.message,
chatDto.conversationId,
)) {
res.write(
`data: ${JSON.stringify({
message: content,
})}\n\n`,
);
}
res.end();
}
}