|
| 1 | +from collections.abc import Callable |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from mpt_api_client.http.collection import CollectionBaseClient |
| 5 | + |
| 6 | +ItemType = type[CollectionBaseClient[Any]] |
| 7 | + |
| 8 | + |
| 9 | +class Registry: |
| 10 | + """Registry for MPT collection clients.""" |
| 11 | + |
| 12 | + def __init__(self) -> None: |
| 13 | + self.items: dict[str, ItemType] = {} # noqa: WPS110 |
| 14 | + |
| 15 | + def __call__(self, keyname: str) -> Callable[[ItemType], ItemType]: |
| 16 | + """Decorator to register a CollectionBaseClient class. |
| 17 | +
|
| 18 | + Args: |
| 19 | + keyname: The key to register the class under |
| 20 | +
|
| 21 | + Returns: |
| 22 | + The decorator function |
| 23 | +
|
| 24 | + Examples: |
| 25 | + registry = Registry() |
| 26 | + @registry("orders") |
| 27 | + class OrderCollectionClient(CollectionBaseClient): |
| 28 | + _endpoint = "/api/v1/orders" |
| 29 | + _resource_class = Order |
| 30 | +
|
| 31 | + registry.get("orders") == OrderCollectionClient |
| 32 | + """ |
| 33 | + |
| 34 | + def decorator(cls: ItemType) -> ItemType: |
| 35 | + self.register(keyname, cls) |
| 36 | + return cls |
| 37 | + |
| 38 | + return decorator |
| 39 | + |
| 40 | + def register(self, keyname: str, item: ItemType) -> None: # noqa: WPS110 |
| 41 | + """Register a collection client class with a keyname. |
| 42 | +
|
| 43 | + Args: |
| 44 | + keyname: The key to register the client under |
| 45 | + item: The collection client class to register |
| 46 | + """ |
| 47 | + self.items[keyname] = item |
| 48 | + |
| 49 | + def get(self, keyname: str) -> ItemType: |
| 50 | + """Get a registered collection client class by keyname. |
| 51 | +
|
| 52 | + Args: |
| 53 | + keyname: The key to look up |
| 54 | +
|
| 55 | + Returns: |
| 56 | + The registered collection client class |
| 57 | +
|
| 58 | + Raises: |
| 59 | + KeyError: If keyname is not registered |
| 60 | + """ |
| 61 | + if keyname not in self.items: |
| 62 | + raise KeyError(f"No collection client registered with keyname: {keyname}") |
| 63 | + return self.items[keyname] |
| 64 | + |
| 65 | + def list_keys(self) -> list[str]: |
| 66 | + """Get all registered keynames. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + List of all registered keynames |
| 70 | + """ |
| 71 | + return list(self.items.keys()) |
| 72 | + |
| 73 | + |
| 74 | +commerce = Registry() |
0 commit comments