Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

refactor(api): type shared list query inputs

Juan Denis96d11be8bb8e
diff --git a/backend/app/api/_query.py b/backend/app/api/_query.py
index 9e0879bd..065874b5 100644
--- a/backend/app/api/_query.py
+++ b/backend/app/api/_query.py
@@ -37,6 +37,7 @@ endpoint behaves exactly as it did before.
"""
import re
+from dataclasses import dataclass
from datetime import datetime, timedelta
from sqlalchemy import and_, or_, inspect
@@ -60,6 +61,48 @@ class QueryParseError(ValueError):
"""A malformed query parameter. API layers turn this into a 400."""
+@dataclass(frozen=True)
+class ListQuery:
+ """Typed representation of the shared list-query parameters.
+
+ Existing endpoints may keep passing a Flask request to ``apply_query``.
+ Schema-backed endpoints can parse this value once and pass it directly, so
+ the query layer no longer requires a Flask request global.
+ """
+
+ select: str | None = None
+ filter: str | None = None
+ orderby: str | None = None
+ skip: int = 0
+ top: int | None = None
+
+ def __post_init__(self):
+ if self.skip < 0:
+ raise QueryParseError('$skip cannot be negative.')
+ if self.top is not None and self.top < 0:
+ raise QueryParseError('$top cannot be negative.')
+ if self.top is not None and self.top > MAX_TOP:
+ object.__setattr__(self, 'top', MAX_TOP)
+
+ @classmethod
+ def from_args(cls, args, *, default_top=None):
+ """Parse a MultiDict-like mapping into one validated value."""
+ top = _int_arg(args.get('$top'), default_top, '$top')
+ if top is not None:
+ top = max(0, min(top, MAX_TOP))
+ return cls(
+ select=args.get('$select'),
+ filter=args.get('$filter'),
+ orderby=args.get('$orderby'),
+ skip=_int_arg(args.get('$skip'), 0, '$skip'),
+ top=top,
+ )
+
+ @classmethod
+ def from_request(cls, http_request, *, default_top=None):
+ return cls.from_args(http_request.args, default_top=default_top)
+
+
def _columns(model):
"""The model's real mapped columns — and the field allowlist."""
return {c.key: getattr(model, c.key) for c in inspect(model).mapper.column_attrs}
@@ -244,9 +287,12 @@ class QueryResult:
return {'total': self.total, 'skip': self.skip, 'top': self.top}
-def apply_query(query, model, request, *, default_top=None, select_extra=()):
+def apply_query(query, model, request_or_query, *, default_top=None, select_extra=()):
"""Apply the query params present on `request` to `query`.
+ ``request_or_query`` accepts either Flask's request object or a pre-parsed
+ :class:`ListQuery` from a schema-backed endpoint.
+
Returns a :class:`QueryResult`. With no params present this is a no-op and
``.fields`` is None, so an endpoint can adopt it without changing any
existing caller's response.
@@ -254,24 +300,27 @@ def apply_query(query, model, request, *, default_top=None, select_extra=()):
`default_top` bounds an endpoint that has no explicit ``$top``; leave it
None to keep today's unbounded behaviour while callers migrate.
"""
- args = request.args
- where = parse_filter(args.get('$filter'), model)
+ list_query = (
+ request_or_query
+ if isinstance(request_or_query, ListQuery)
+ else ListQuery.from_request(request_or_query, default_top=default_top)
+ )
+
+ where = parse_filter(list_query.filter, model)
if where is not None:
query = query.filter(where)
- order = parse_orderby(args.get('$orderby'), model)
+ order = parse_orderby(list_query.orderby, model)
if order:
query = query.order_by(*order)
- fields = parse_select(args.get('$select'), model, extra=select_extra)
+ fields = parse_select(list_query.select, model, extra=select_extra)
# `total` is the count BEFORE paging — the client needs it to render "12 of
# 340", and computing it after .limit() would just return the page size.
total = None
- skip = _int_arg(args.get('$skip'), 0, '$skip')
- top = _int_arg(args.get('$top'), default_top, '$top')
- if top is not None:
- top = max(0, min(top, MAX_TOP))
+ skip = list_query.skip
+ top = list_query.top
if skip or top is not None:
total = query.order_by(None).count()
if skip:
diff --git a/backend/tests/test_query_layer.py b/backend/tests/test_query_layer.py
index 4c4d2861..eeb0672f 100644
--- a/backend/tests/test_query_layer.py
+++ b/backend/tests/test_query_layer.py
@@ -3,7 +3,8 @@
import pytest
from app.api._query import (
- QueryParseError, apply_query, parse_filter, parse_orderby, parse_select,
+ ListQuery, QueryParseError, apply_query, parse_filter, parse_orderby,
+ parse_select,
)
from app.models import Application
@@ -128,6 +129,30 @@ def test_select_rejects_underived_unknown_field(app):
# ------------------------------------------------------------- apply_query
+def test_list_query_parses_and_caps_paging():
+ parsed = ListQuery.from_args({
+ '$select': 'id,name',
+ '$filter': "name eq 'demo'",
+ '$orderby': 'name desc',
+ '$skip': '4',
+ '$top': '99999',
+ })
+
+ assert parsed == ListQuery(
+ select='id,name',
+ filter="name eq 'demo'",
+ orderby='name desc',
+ skip=4,
+ top=500,
+ )
+
+
+def test_list_query_rejects_invalid_paging_before_touching_orm():
+ with pytest.raises(QueryParseError):
+ ListQuery.from_args({'$top': 'many'})
+ with pytest.raises(QueryParseError):
+ ListQuery.from_args({'$skip': '-1'})
+
def test_apply_query_is_a_noop_without_params(app):
"""Adoption must not change any existing caller's response."""
with app.app_context():
@@ -159,6 +184,18 @@ def test_apply_query_counts_before_paging(app):
assert result.top == 1
+def test_apply_query_accepts_typed_query_without_flask_request(app):
+ with app.app_context():
+ result = apply_query(
+ Application.query,
+ Application,
+ ListQuery(orderby='name desc', top=1),
+ )
+
+ assert result.top == 1
+ assert result.total is not None
+
+
# ------------------------------------------------- to_dict field narrowing
def test_to_dict_full_payload_is_unchanged_by_default(app, sample_app):