-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhero_service.py
56 lines (47 loc) · 1.89 KB
/
hero_service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from typing import List, Optional
import uuid
import asyncio
from models import *
from logger import *
class HeroService:
def __init__(self):
# In-memory structure to store heroes
self.heroes_db: List[Hero] = []
# Lock to handle concurrent access
self.lock = asyncio.Lock()
async def create_hero(self, hero: Hero) -> Hero:
async with self.lock:
hero.id = str(uuid.uuid4())
self.heroes_db.append(hero)
logger.info(f"Hero '{hero.name}' created with ID: {hero.id}")
return hero
async def get_hero(self, hero_id: str) -> Optional[Hero]:
async with self.lock:
hero = next((h for h in self.heroes_db if h.id == hero_id), None)
if hero:
logger.info(f"Hero '{hero_id}' retrieved.")
else:
logger.warning(f"Hero '{hero_id}' not found.")
return hero
async def list_heroes(self) -> List[Hero]:
async with self.lock:
logger.info(f"Listing all heroes. Total count: {len(self.heroes_db)}")
return self.heroes_db.copy()
async def delete_hero(self, hero_id: str) -> bool:
async with self.lock:
hero = next((h for h in self.heroes_db if h.id == hero_id), None)
if hero:
self.heroes_db.remove(hero)
logger.info(f"Hero '{hero_id}' deleted.")
return True
else:
logger.warning(f"Hero '{hero_id}' not found for deletion.")
return False
async def query_heroes_fireball_low_ac(self) -> List[Hero]:
async with self.lock:
results = [
hero for hero in self.heroes_db
if "Fireball" in hero.spells and hero.armor_class < 20
]
logger.info(f"Found {len(results)} heroes with Fireball and AC < 20.")
return results