feat(jobs): paginate jobs list
This commit is contained in:
@@ -6,6 +6,36 @@ from rest_framework.test import APIClient
|
||||
from jobs.services import create_job
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_jobs_use_limit_offset_pagination():
|
||||
create_job(job_type="demo.success")
|
||||
create_job(job_type="demo.fail")
|
||||
create_job(job_type="demo.slow")
|
||||
|
||||
response = APIClient().get("/api/jobs/?limit=2")
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["count"] == 3
|
||||
assert body["next"] is not None
|
||||
assert body["previous"] is None
|
||||
assert len(body["results"]) == 2
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_jobs_pagination_supports_status_and_type_filters():
|
||||
create_job(job_type="demo.success")
|
||||
create_job(job_type="demo.fail")
|
||||
create_job(job_type="demo.slow")
|
||||
|
||||
response = APIClient().get("/api/jobs/?status=queued&type=success&limit=10")
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["count"] == 1
|
||||
assert body["results"][0]["type"] == "demo.success"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_global_events_use_cursor_pagination():
|
||||
create_job(job_type="demo.success")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from django.db import connection
|
||||
from rest_framework import generics, status
|
||||
from rest_framework.exceptions import NotFound, ValidationError
|
||||
from rest_framework.pagination import CursorPagination
|
||||
from rest_framework.pagination import CursorPagination, LimitOffsetPagination
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
@@ -17,6 +17,11 @@ class JobEventCursorPagination(CursorPagination):
|
||||
ordering = "-id"
|
||||
|
||||
|
||||
class JobLimitOffsetPagination(LimitOffsetPagination):
|
||||
default_limit = 25
|
||||
max_limit = 100
|
||||
|
||||
|
||||
class HealthAPIView(APIView):
|
||||
def get(self, request):
|
||||
try:
|
||||
@@ -35,9 +40,15 @@ class JobListCreateAPIView(APIView):
|
||||
def get(self, request):
|
||||
queryset = Job.objects.order_by("-created_at")
|
||||
status_filter = request.query_params.get("status")
|
||||
type_filter = request.query_params.get("type")
|
||||
if status_filter:
|
||||
queryset = queryset.filter(status=status_filter)
|
||||
return Response(JobSerializer(queryset, many=True).data)
|
||||
if type_filter:
|
||||
queryset = queryset.filter(type__icontains=type_filter)
|
||||
|
||||
paginator = JobLimitOffsetPagination()
|
||||
page = paginator.paginate_queryset(queryset, request, view=self)
|
||||
return paginator.get_paginated_response(JobSerializer(page, many=True).data)
|
||||
|
||||
def post(self, request):
|
||||
serializer = JobCreateSerializer(data=request.data)
|
||||
|
||||
Reference in New Issue
Block a user