acupedia-api/app/cache/content_cache.py

26 lines
2.1 KiB
Python

from __future__ import annotations
from typing import Any, Awaitable, Callable
from uuid import UUID
from pydantic import BaseModel
from .service import CacheService
class ContentCache:
def __init__(self, cache: CacheService) -> None: self.cache = cache
@staticmethod
def _dto_loader(loader: Callable[[], Awaitable[BaseModel]]):
async def wrapped() -> dict[str, Any]:
return (await loader()).model_dump(mode="json", by_alias=True)
return wrapped
async def active_modules(self, *, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.active_modules(), loader=self._dto_loader(loader), ttl_seconds=self.cache.settings.modules_ttl_seconds)
async def module_contents(self, *, module_id: UUID, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.module_contents(module_id), loader=self._dto_loader(loader), ttl_seconds=self.cache.settings.module_contents_ttl_seconds)
async def module_template_contents(self, *, module_id: UUID, template_code: str, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.module_template_contents(module_id=module_id, template_code=template_code), loader=self._dto_loader(loader), ttl_seconds=self.cache.settings.module_contents_ttl_seconds)
async def module_template_details(self, *, module_id: UUID, template_code: str, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.module_template_details(module_id=module_id, template_code=template_code), loader=self._dto_loader(loader), ttl_seconds=self.cache.settings.module_contents_ttl_seconds)
async def template_definitions(self, *, template_code: str, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.template_definitions(template_code), loader=self._dto_loader(loader), ttl_seconds=self.cache.settings.template_definitions_ttl_seconds)
async def content_detail(self, *, content_id: UUID, loader):
return await self.cache.get_or_set_json(key=self.cache.keys.content_detail(content_id), loader=loader, ttl_seconds=self.cache.settings.content_detail_ttl_seconds)