diff options
Diffstat (limited to 'libs/fsm.py')
| -rw-r--r-- | libs/fsm.py | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/libs/fsm.py b/libs/fsm.py new file mode 100644 index 0000000..00ccacb --- /dev/null +++ b/libs/fsm.py | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | from contextlib import asynccontextmanager | ||
| 2 | |||
| 3 | from aiogram.fsm.context import FSMContext | ||
| 4 | from pydantic.main import BaseModel | ||
| 5 | from typing_extensions import AsyncGenerator | ||
| 6 | |||
| 7 | |||
| 8 | async def set_data(state: FSMContext, model: BaseModel) -> None: | ||
| 9 | await state.set_data(model.model_dump()) | ||
| 10 | |||
| 11 | |||
| 12 | async def get_data[T: BaseModel](state: FSMContext, model_type: type[T]) -> T: | ||
| 13 | return model_type.model_validate(await state.get_data()) | ||
| 14 | |||
| 15 | |||
| 16 | @asynccontextmanager | ||
| 17 | async def edit_data[T: BaseModel]( | ||
| 18 | state: FSMContext, | ||
| 19 | model_type: type[T], | ||
| 20 | ) -> AsyncGenerator[T]: | ||
| 21 | model = await get_data(state, model_type) | ||
| 22 | yield model | ||
| 23 | await set_data(state, model) | ||
