Files
yourpart3/backend/controllers/chatController.js
2024-09-21 15:26:29 +02:00

86 lines
2.2 KiB
JavaScript

import {
getMessages as getMessagesService,
findMatch,
registerUser as registerUserService,
addMessage,
endChat,
removeUser as removeUserService
} from '../services/chatService.js';
class ChatController {
constructor() {
this.getMessages = this.getMessages.bind(this);
this.findRandomChatMatch = this.findRandomChatMatch.bind(this);
this.registerUser = this.registerUser.bind(this);
this.sendMessage = this.sendMessage.bind(this);
this.stopChat = this.stopChat.bind(this);
this.removeUser = this.removeUser.bind(this);
}
async getMessages(req, res) {
const { to, from } = req.body;
try {
const messages = await getMessagesService(to, from);
res.status(200).json(messages);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async findRandomChatMatch(req, res) {
const { genders, age, id } = req.body;
try {
const match = await findMatch(genders, age, id);
if (match) {
res.status(200).json({ status: 'matched', user: match });
} else {
res.status(200).json({ status: 'waiting' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async registerUser(req, res) {
const { gender, age } = req.body;
try {
const userId = await registerUserService(gender, age);
res.status(200).json({ id: userId });
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async sendMessage(req, res) {
const { from, to, text } = req.body;
try {
const message = await addMessage(from, to, text);
res.status(200).json(message);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async removeUser(req, res) {
const { id } = req.body;
try {
await removeUserService(id);
res.sendStatus(200);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async stopChat(req, res) {
const { id } = req.body;
try {
await endChat(id);
res.sendStatus(200);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
}
export default ChatController;