|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from importlib import import_module |
| 3 | +from typing import Any, Dict |
| 4 | + |
| 5 | + |
| 6 | +class Adapter(ABC): |
| 7 | + @abstractmethod |
| 8 | + def parse_input(self, request: Dict[str, Any]) -> Any: |
| 9 | + """This function parses the data retrieved from the request. |
| 10 | +
|
| 11 | + Args: |
| 12 | + request: The request response as a dictionary. |
| 13 | +
|
| 14 | + Returns: |
| 15 | + A parsed set of data. |
| 16 | + """ |
| 17 | + pass |
| 18 | + |
| 19 | + @abstractmethod |
| 20 | + def verify_output(self, input_: Any, output: Any) -> None: |
| 21 | + """This function verifies the adapter's output to assure a proper response can be given. |
| 22 | +
|
| 23 | + If the output fails verification, this function should raise an exception. |
| 24 | +
|
| 25 | + Args: |
| 26 | + input_: The request input data from BandChain. |
| 27 | + output: The output to be returned to the data source requestor. |
| 28 | + """ |
| 29 | + pass |
| 30 | + |
| 31 | + @abstractmethod |
| 32 | + def parse_output(self, output: Any) -> Any: |
| 33 | + """This function parses the output retrieved from the adapter's set endpoint. |
| 34 | +
|
| 35 | + Args: |
| 36 | + output: Output from the adapter's endpoint. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + The parsed output to be sent back to the data source. |
| 40 | + """ |
| 41 | + pass |
| 42 | + |
| 43 | + @abstractmethod |
| 44 | + async def call(self, input_: Any) -> Any: |
| 45 | + """This function calls the adapter's set endpoint to retrieve the requested data. |
| 46 | +
|
| 47 | + Args: |
| 48 | + input_: The input from request from the data source. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + The raw data from the adapter's endpoint. |
| 52 | + """ |
| 53 | + pass |
| 54 | + |
| 55 | + async def unified_call(self, request: Dict[str, Any]) -> Any: |
| 56 | + input_ = self.parse_input(request) |
| 57 | + output = await self.call(input_) |
| 58 | + self.verify_output(input_, output) |
| 59 | + return self.parse_output(output) |
| 60 | + |
| 61 | + |
| 62 | +def init_adapter(adapter_type: str, adapter_name: str) -> Adapter: |
| 63 | + # check adapter configuration |
| 64 | + if not adapter_type: |
| 65 | + raise Exception("MISSING 'ADAPTER_TYPE' ENV") |
| 66 | + if not adapter_name: |
| 67 | + raise Exception("MISSING 'ADAPTER_NAME' ENV") |
| 68 | + |
| 69 | + module = import_module(f"adapter.{adapter_type}.{adapter_name}".lower()) |
| 70 | + AdapterClass = getattr(module, "".join([part.capitalize() for part in adapter_name.split("_")])) |
| 71 | + return AdapterClass() |
0 commit comments