|
| 1 | +from redis.asyncio import Redis |
| 2 | +from redis.commands.search.field import TextField |
| 3 | +from redis.commands.search.indexDefinition import IndexDefinition, IndexType |
| 4 | +from redis.exceptions import ResponseError |
| 5 | + |
| 6 | +from app.logger import logger |
| 7 | + |
| 8 | +TODOS_INDEX = "todos-idx" |
| 9 | +TODOS_PREFIX = "todos:" |
| 10 | + |
| 11 | + |
| 12 | +class Todos: |
| 13 | + """Stores todos""" |
| 14 | + |
| 15 | + def __init__(self, redis: Redis): |
| 16 | + self.redis = redis |
| 17 | + |
| 18 | + async def initialize(self) -> None: |
| 19 | + await self.create_index_if_not_exists() |
| 20 | + return None |
| 21 | + |
| 22 | + async def have_index(self) -> bool: |
| 23 | + try: |
| 24 | + await self.redis.ft(TODOS_INDEX).info() # type: ignore |
| 25 | + except ResponseError as e: |
| 26 | + if "Unknown index name" not in str(e): |
| 27 | + logger.info(f"Index {TODOS_INDEX} already exists") |
| 28 | + raise |
| 29 | + |
| 30 | + return True |
| 31 | + |
| 32 | + async def create_index_if_not_exists(self) -> None: |
| 33 | + try: |
| 34 | + if await self.have_index(): |
| 35 | + return None |
| 36 | + |
| 37 | + logger.debug(f"Creating index {TODOS_INDEX}") |
| 38 | + |
| 39 | + schema = ( |
| 40 | + TextField("$.name", as_name="name"), |
| 41 | + TextField("$.status", as_name="status"), |
| 42 | + ) |
| 43 | + |
| 44 | + await self.redis.ft(TODOS_INDEX).create_index( # type: ignore |
| 45 | + schema, |
| 46 | + definition=IndexDefinition( # type: ignore |
| 47 | + prefix=[TODOS_PREFIX], index_type=IndexType.JSON |
| 48 | + ), |
| 49 | + ) |
| 50 | + |
| 51 | + logger.debug(f"Index {TODOS_INDEX} created successfully") |
| 52 | + except Exception as e: |
| 53 | + logger.error(f"Error setting up index {TODOS_INDEX}: {e}") |
| 54 | + raise |
| 55 | + |
| 56 | + return None |
0 commit comments