front/stubs/api/db.js

75 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2024-10-03 22:35:39 +03:00
// Read already defined users (pseudo-DB)
const users = require('./auth/users.json');
2024-10-04 00:06:44 +03:00
const chats = require('./chat/chats.json');
2024-10-03 22:35:39 +03:00
const getUserFromDB = (userID) => {
if (!userID) {return false;}
// Accessing 'DB'
const user = users.find((user) => user.id === userID);
if (user) {
return user;
} else {
return false;
}
}
2024-10-04 11:21:21 +03:00
const deleteUserFromDB = (userID) => {
const index = users.findIndex(item => item.id === userID);
if (index !== -1) {
users.splice(index, 1);
}
}
const addUserToDB = (user) => {
users.push(user);
}
2024-10-04 00:06:44 +03:00
const getChatFromDB = (firstID, secondID) => {
if (!firstID || !secondID) {return false;}
// Accessing 'DB'
const chat = chats.find((item) =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
if (chat) {
return chat;
} else {
return false;
}
}
2024-10-04 11:21:21 +03:00
const getUsersChats = (userID) => {
if (!userID) {return false;}
const userChats = chats.filter((chat) => (chat.id1 === userID || chat.id2 === userID));
if (userChats) {
return userChats;
} else {
return false;
}
}
2024-10-05 11:46:18 +03:00
const addMessageToChat = (chat, msg) => {
chat.messages.push(msg);
}
2024-10-04 11:21:21 +03:00
const deleteChatFromDB = (firstID, secondID) => {
const index = chats.findIndex(item =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
if (index !== -1) {
chats.splice(index, 1);
}
}
const addChatToDB = (chat) => {
chats.push(chat);
}
module.exports = {users, chats, getUserFromDB, getChatFromDB, addUserToDB,
2024-10-05 11:46:18 +03:00
deleteUserFromDB, addChatToDB, deleteChatFromDB, getUsersChats, addMessageToChat}