2021-09-25 16:49:11 +02:00
|
|
|
from typing import Iterable, Optional
|
|
|
|
|
2021-10-06 19:44:03 +02:00
|
|
|
from bot.message.messageData import MessageData
|
2021-09-25 16:49:11 +02:00
|
|
|
from database.client import Client
|
|
|
|
from entity.user import User
|
|
|
|
from exception.notFoundException import NotFoundException
|
|
|
|
|
|
|
|
|
|
|
|
class UserRepository():
|
|
|
|
client: Client
|
|
|
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
self.client = Client()
|
|
|
|
|
2021-09-28 17:03:11 +02:00
|
|
|
def get_by_id(self, id: str) -> User:
|
|
|
|
user = self.client.find_one(
|
2021-09-25 16:49:11 +02:00
|
|
|
User.collection,
|
|
|
|
{
|
2021-09-28 17:03:11 +02:00
|
|
|
User.id_index: id
|
2021-09-25 16:49:11 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
if not user:
|
|
|
|
raise NotFoundException(f'Could not find user with "{id}" id')
|
|
|
|
|
|
|
|
return User(
|
2021-09-28 17:03:11 +02:00
|
|
|
user[User.id_index],
|
|
|
|
user[User.username_index],
|
|
|
|
user[User.chats_index]
|
2021-09-25 16:49:11 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def save(self, user: User) -> None:
|
2021-09-28 17:03:11 +02:00
|
|
|
self.client.update_one(
|
2021-09-25 16:49:11 +02:00
|
|
|
User.collection,
|
2021-09-28 17:03:11 +02:00
|
|
|
{ User.id_index: user.user_id },
|
|
|
|
user.to_mongo_document()
|
2021-09-25 16:49:11 +02:00
|
|
|
)
|
|
|
|
|
2021-10-06 19:44:03 +02:00
|
|
|
def save_by_message_data(self, data: MessageData) -> None:
|
2021-09-28 17:03:11 +02:00
|
|
|
self.client.insert_one(
|
2021-09-25 16:49:11 +02:00
|
|
|
User.collection,
|
|
|
|
{
|
2021-09-28 17:03:11 +02:00
|
|
|
User.id_index: data.user_id,
|
|
|
|
User.username_index: data.username,
|
|
|
|
User.chats_index: [data.chat_id]
|
2021-09-25 16:49:11 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-09-28 17:03:11 +02:00
|
|
|
def get_all_for_chat(self, chat_id: str) -> Iterable[User]:
|
2021-09-25 16:49:11 +02:00
|
|
|
result = []
|
2021-09-28 17:03:11 +02:00
|
|
|
users = self.client.find_many(
|
2021-09-25 16:49:11 +02:00
|
|
|
User.collection,
|
|
|
|
{
|
2021-09-28 17:03:11 +02:00
|
|
|
User.chats_index: {
|
|
|
|
"$in" : [chat_id]
|
2021-09-25 16:49:11 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
for record in users:
|
2021-09-28 17:03:11 +02:00
|
|
|
result.append(User.from_mongo_document(record))
|
2021-09-25 16:49:11 +02:00
|
|
|
|
|
|
|
return result
|