2024-10-04 00:06:44 +03:00
|
|
|
const chatRouter = require('express').Router();
|
|
|
|
|
|
|
|
module.exports = chatRouter;
|
|
|
|
|
2024-10-05 11:46:18 +03:00
|
|
|
const { getChatFromDB, getUsersChats, addChatToDB, getUserFromDB,
|
|
|
|
addMessageToChat} = require('../db');
|
2024-10-04 00:06:44 +03:00
|
|
|
|
2024-10-04 11:21:21 +03:00
|
|
|
chatRouter.get('/item/:id1/:id2', (req, res) => {
|
2024-10-04 00:06:44 +03:00
|
|
|
const { id1, id2 } = req.params;
|
2024-10-05 11:46:18 +03:00
|
|
|
|
|
|
|
if (id1 === id2) {
|
|
|
|
res.status(400).send({message: 'Ids should be different'});
|
|
|
|
return;
|
|
|
|
}
|
2024-10-04 00:06:44 +03:00
|
|
|
|
|
|
|
const chat = getChatFromDB(id1, id2);
|
|
|
|
|
|
|
|
if (chat) {
|
|
|
|
res.status(200).send({chat});
|
|
|
|
} else {
|
|
|
|
res.status(404).send({message: 'Chat was not found'});
|
|
|
|
}
|
|
|
|
})
|
2024-10-04 11:21:21 +03:00
|
|
|
|
|
|
|
chatRouter.post('/item/:id1/:id2', (req, res) => {
|
|
|
|
const { id1, id2 } = req.params;
|
2024-10-05 11:46:18 +03:00
|
|
|
|
|
|
|
if (id1 === id2) {
|
|
|
|
res.status(400).send({message: 'Ids should be different'});
|
|
|
|
return;
|
|
|
|
}
|
2024-10-04 11:21:21 +03:00
|
|
|
|
|
|
|
const chat = getChatFromDB(id1, id2);
|
|
|
|
|
|
|
|
if (chat) {
|
|
|
|
// Chat already exists
|
|
|
|
res.status(200).send({chat});
|
|
|
|
} else {
|
2024-10-04 14:29:00 +03:00
|
|
|
if (!getUserFromDB(id1) || !getUserFromDB(id2)) {
|
|
|
|
res.status(404).send({message: 'Such interlocutor does not exist'});
|
|
|
|
} else {
|
|
|
|
// Creating new chat
|
|
|
|
const newChat = {
|
|
|
|
id1: id1,
|
|
|
|
id2: id2,
|
|
|
|
messages: []
|
|
|
|
}
|
|
|
|
|
|
|
|
addChatToDB(newChat);
|
|
|
|
|
|
|
|
res.status(200).send({newChat});
|
2024-10-04 11:21:21 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
chatRouter.get('/list/:id', (req, res) => {
|
|
|
|
const { id } = req.params;
|
|
|
|
|
|
|
|
const userChats = getUsersChats(id);
|
|
|
|
|
|
|
|
if (!userChats) {
|
|
|
|
res.status(404).send({message: 'Error with retrieving chats'});
|
|
|
|
} else {
|
|
|
|
res.status(200).send({chats: userChats});
|
|
|
|
}
|
|
|
|
})
|
2024-10-05 11:46:18 +03:00
|
|
|
|
|
|
|
chatRouter.post('/message/:sender/:receiver', (req, res) => {
|
|
|
|
const { sender, receiver } = req.params;
|
|
|
|
const { message } = req.body;
|
|
|
|
|
|
|
|
const chat = getChatFromDB(sender, receiver);
|
|
|
|
|
|
|
|
if (!chat) {
|
|
|
|
// Chat already exists
|
|
|
|
res.status(400).send({message: "Such chat does not exist"});
|
|
|
|
} else {
|
|
|
|
if (!getUserFromDB(sender) || !getUserFromDB(receiver)) {
|
|
|
|
res.status(404).send({message: 'Such people do not exist'});
|
|
|
|
} else {
|
|
|
|
// Add new message
|
|
|
|
addMessageToChat(chat, message);
|
|
|
|
res.status(200).send({});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|