|
3 | 3 | from collections.abc import Awaitable, Callable, Coroutine |
4 | 4 | from dataclasses import dataclass |
5 | 5 | from functools import wraps |
6 | | -from typing import Any, NoReturn, ParamSpec, TypeVar, cast |
| 6 | +from typing import Any, Concatenate, NoReturn, ParamSpec, TypeVar, cast |
7 | 7 |
|
| 8 | +from pydantic import BaseModel |
8 | 9 | from sanic import Request, json |
9 | 10 | from sanic.response import JSONResponse |
| 11 | +from sanic_ext import validate |
10 | 12 |
|
11 | 13 | from renku_data_services import errors |
12 | 14 | from renku_data_services.base_api.blueprint import BlueprintFactoryResponse, CustomBlueprint |
@@ -69,3 +71,29 @@ async def decorated_function(*args: _P.args, **kwargs: _P.kwargs) -> _T: |
69 | 71 | return response |
70 | 72 |
|
71 | 73 | return decorated_function |
| 74 | + |
| 75 | + |
| 76 | +def validate_query( |
| 77 | + query: type[BaseModel], |
| 78 | +) -> Callable[ |
| 79 | + [Callable[Concatenate[Request, _P], Awaitable[_T]]], |
| 80 | + Callable[Concatenate[Request, _P], Coroutine[Any, Any, _T]], |
| 81 | +]: |
| 82 | + """Decorator for sanic query parameter validation. |
| 83 | +
|
| 84 | + Should be removed once sanic fixes this error in their validation code. |
| 85 | + """ |
| 86 | + |
| 87 | + def decorator( |
| 88 | + f: Callable[Concatenate[Request, _P], Awaitable[_T]], |
| 89 | + ) -> Callable[Concatenate[Request, _P], Coroutine[Any, Any, _T]]: |
| 90 | + @wraps(f) |
| 91 | + async def decorated_function(request: Request, *args: _P.args, **kwargs: _P.kwargs) -> _T: |
| 92 | + try: |
| 93 | + return await validate(query=query)(f)(request, *args, **kwargs) |
| 94 | + except KeyError: |
| 95 | + raise errors.ValidationError(message="Failed to validate the query parameters") |
| 96 | + |
| 97 | + return decorated_function |
| 98 | + |
| 99 | + return decorator |
0 commit comments