Coverage for zombie_nomnom_api/graphql_app/dependencies.py: 100%
32 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-07 04:25 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-07 04:25 +0000
1from functools import cache
2from typing import Any
4from zombie_nomnom_api import configs
5from zombie_nomnom_api.game import GameMakerInterface, create_maker
6from zombie_nomnom.engine import DrawDice, Score
8_unset = object()
11class DIContainer:
12 def __init__(self) -> None:
13 self._dependencies = {}
15 def __getitem__(self, key: Any) -> Any:
16 value = self.get(key, _unset)
17 if value is _unset:
18 raise KeyError(key)
19 return value
21 def __setitem__(self, key: Any, value: Any) -> None:
22 self.register(key, value)
24 def register(self, key: type | str, value: Any = None) -> None:
25 if isinstance(key, str) and not value:
26 raise ValueError("value must be provided if key is a string")
27 self._dependencies[str(key)] = value or key
29 def get(self, key: Any, default: Any = None) -> Any:
30 value = self._dependencies.get(str(key), default)
31 if isinstance(value, type):
32 # TODO(Milo): Handle dependency injection for anything the constructor needs.
33 value = self._dependencies[str(key)] = value()
34 return value
37@cache
38def bootstrap() -> DIContainer:
39 container = DIContainer()
40 container[GameMakerInterface] = create_maker(configs.game_maker_type)
41 container[DrawDice] = DrawDice()
42 container[Score] = Score()
43 return container