diff --git a/src/core/router.py b/src/core/router.py new file mode 100644 index 0000000..3f8c289 --- /dev/null +++ b/src/core/router.py @@ -0,0 +1,38 @@ +import re +from typing import Optional, Dict, Tuple, List, Any +from src.models.endpoint import Endpoint + + +class Router: + def __init__(self): + self.routes: List[Tuple[re.Pattern, Endpoint, Dict[str, str]]] = [] + self._compile_regex() + + def _path_to_regex(self, path: str) -> Tuple[str, Dict[str, str]]: + param_names = {} + regex_path = re.sub(r"\{(\w+)\}", lambda m: param_names.__setitem__(m.group(1), m.group(0)) or "(?P<" + m.group(1) + ">[^/]+)", path) + regex_path = f"^{regex_path}$" + return regex_path, param_names + + def _compile_regex(self): + pass + + def add_route(self, endpoint: Endpoint): + pattern, param_names = self._path_to_regex(endpoint.path) + compiled = re.compile(pattern) + self.routes.append((compiled, endpoint, param_names)) + + def match(self, path: str, method: str) -> Optional[Tuple[Endpoint, Dict[str, str]]]: + for compiled_pattern, endpoint, param_names in self.routes: + if endpoint.method.upper() != method.upper(): + continue + match = compiled_pattern.match(path) + if match: + return endpoint, match.groupdict() + return None + + def get_all_routes(self) -> List[Endpoint]: + return [endpoint for _, endpoint, _ in self.routes] + + def clear(self): + self.routes.clear()