Create a routes constants file and a router for getting routes in app

This commit is contained in:
Campbell Alden 2026-08-05 00:12:47 +09:00
parent 790e0a1ce5
commit 5a4f9dc250
5 changed files with 93 additions and 10 deletions

19
src/services/router.py Normal file
View file

@ -0,0 +1,19 @@
from src.constants.routes import Route
class Router:
def __init__(self, host: str, port: int | None):
self._host = host
self._port = port
def interpolate_url[Params](self, route: Route[Params], params: Params, **query_params) -> str:
query_strs = []
for key, value in query_params.items():
query_strs.append(f'{key}={value}')
query_str = '&'.join(query_strs)
query_str = f'?{query_str}' if len(query_str) > 0 else query_str
return f'{self._host}{"" if self._port is None else f":{self._port}"}{route.interpolate(params)}{query_str}'
def get_url(self, route: Route[None], **query_params):
return self.interpolate_url(route, None, **query_params)

View file

@ -1,3 +1,6 @@
from src.services.router import Router
from typing import TypedDict, Unpack
from src.constants.routes import ROUTES
from src.services.auth import AuthService, EmailConfirmationClaim, JWT
from email.headerregistry import Address
from jinja2 import Environment, PackageLoader, select_autoescape
@ -23,11 +26,19 @@ def is_valid_password(password: str) -> bool:
return long_enough and short_enough and has_symbol
class ServiceDeps(TypedDict):
repo: UserRepo
email_service: EmailService
auth_service: AuthService
router: Router
class UserService:
def __init__(self, repo: UserRepo, email_service: EmailService, auth_service: AuthService):
self._repo = repo
self._email_service = email_service
self._auth_service = auth_service
def __init__(self, **kwargs: Unpack[ServiceDeps]):
self._repo = kwargs['repo']
self._email_service = kwargs['email_service']
self._auth_service = kwargs['auth_service']
self._router = kwargs['router']
def login(self, user: UserDTO) -> UserProfile:
full_user = self._repo.auth_as_user(user)
@ -66,8 +77,7 @@ class UserService:
html_template = env.get_template('mail/confirmation_email.html')
token = self._auth_service.mint_claim_from_user(EmailConfirmationClaim, user)
# TODO: Parameterize this with configuration that also drives the API
url = f'/confirm?token={token}'
url = self._router.get_url(ROUTES['confirm_email'], token=token)
text_content = text_template.render(confirmation_link=url)
html_content = html_template.render(confirmation_link=url)