multy-stub/server/routers/epja-2024-1/enterfront/db.js

75 lines
1.7 KiB
JavaScript
Raw Normal View History

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