|
| 1 | +"""Trails v3 API.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from rest_framework import status |
| 6 | +from rest_framework.decorators import api_view, permission_classes |
| 7 | +from rest_framework.permissions import AllowAny |
| 8 | +from rest_framework.request import Request |
| 9 | +from rest_framework.response import Response |
| 10 | + |
| 11 | +from tenancy.services import for_island |
| 12 | +from trails.services import get_trail, list_pois, list_trails |
| 13 | + |
| 14 | + |
| 15 | +def _require_island(request: Request) -> Response | None: |
| 16 | + if request.island is None: |
| 17 | + return Response( |
| 18 | + {'error': {'code': 'island_required', 'message': 'Island context required'}}, |
| 19 | + status=status.HTTP_400_BAD_REQUEST, |
| 20 | + ) |
| 21 | + return None |
| 22 | + |
| 23 | + |
| 24 | +@api_view(['GET']) |
| 25 | +@permission_classes([AllowAny]) |
| 26 | +def trails_list_view(request: Request) -> Response: |
| 27 | + err = _require_island(request) |
| 28 | + if err: |
| 29 | + return err |
| 30 | + |
| 31 | + difficulty = request.GET.get('difficulty', '').strip() |
| 32 | + limit_raw = request.GET.get('limit', '50').strip() |
| 33 | + try: |
| 34 | + limit = int(limit_raw) |
| 35 | + except ValueError: |
| 36 | + limit = 50 |
| 37 | + |
| 38 | + with for_island(request.island): |
| 39 | + payload = list_trails(difficulty=difficulty, limit=limit) |
| 40 | + return Response(payload) |
| 41 | + |
| 42 | + |
| 43 | +@api_view(['GET']) |
| 44 | +@permission_classes([AllowAny]) |
| 45 | +def trails_pois_view(request: Request) -> Response: |
| 46 | + err = _require_island(request) |
| 47 | + if err: |
| 48 | + return err |
| 49 | + |
| 50 | + category = request.GET.get('category', '').strip() |
| 51 | + limit_raw = request.GET.get('limit', '50').strip() |
| 52 | + try: |
| 53 | + limit = int(limit_raw) |
| 54 | + except ValueError: |
| 55 | + limit = 50 |
| 56 | + |
| 57 | + with for_island(request.island): |
| 58 | + payload = list_pois(category=category, limit=limit) |
| 59 | + return Response(payload) |
| 60 | + |
| 61 | + |
| 62 | +@api_view(['GET']) |
| 63 | +@permission_classes([AllowAny]) |
| 64 | +def trail_detail_view(request: Request, trail_id: int) -> Response: |
| 65 | + err = _require_island(request) |
| 66 | + if err: |
| 67 | + return err |
| 68 | + |
| 69 | + with for_island(request.island): |
| 70 | + payload = get_trail(trail_id) |
| 71 | + if payload is None: |
| 72 | + return Response( |
| 73 | + {'error': {'code': 'not_found', 'message': 'Trail not found'}}, |
| 74 | + status=status.HTTP_404_NOT_FOUND, |
| 75 | + ) |
| 76 | + return Response(payload) |
0 commit comments