1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-23 14:59:36 +02:00

pagination!

This commit is contained in:
Sean Morley 2024-07-11 19:27:03 -04:00
parent 6713d9ef5d
commit a3784ae164
6 changed files with 157 additions and 85 deletions

View file

@ -7,10 +7,23 @@ from .serializers import AdventureSerializer, TripSerializer
from rest_framework.permissions import IsAuthenticated from rest_framework.permissions import IsAuthenticated
from django.db.models import Q, Prefetch from django.db.models import Q, Prefetch
from .permissions import IsOwnerOrReadOnly, IsPublicReadOnly from .permissions import IsOwnerOrReadOnly, IsPublicReadOnly
from rest_framework.pagination import PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
page_size = 6
page_size_query_param = 'page_size'
max_page_size = 1000
from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Q
class AdventureViewSet(viewsets.ModelViewSet): class AdventureViewSet(viewsets.ModelViewSet):
serializer_class = AdventureSerializer serializer_class = AdventureSerializer
permission_classes = [IsOwnerOrReadOnly, IsPublicReadOnly] permission_classes = [IsOwnerOrReadOnly, IsPublicReadOnly]
pagination_class = StandardResultsSetPagination
def get_queryset(self): def get_queryset(self):
return Adventure.objects.filter( return Adventure.objects.filter(
@ -21,24 +34,33 @@ class AdventureViewSet(viewsets.ModelViewSet):
serializer.save(user_id=self.request.user) serializer.save(user_id=self.request.user)
@action(detail=False, methods=['get']) @action(detail=False, methods=['get'])
def visited(self, request): def filtered(self, request):
visited_adventures = Adventure.objects.filter( types = request.query_params.get('types', '').split(',')
type='visited', user_id=request.user.id, trip=None) valid_types = ['visited', 'planned', 'featured']
serializer = self.get_serializer(visited_adventures, many=True) types = [t for t in types if t in valid_types]
return Response(serializer.data)
@action(detail=False, methods=['get']) if not types:
def planned(self, request): return Response({"error": "No valid types provided"}, status=400)
planned_adventures = Adventure.objects.filter(
type='planned', user_id=request.user.id, trip=None)
serializer = self.get_serializer(planned_adventures, many=True)
return Response(serializer.data)
@action(detail=False, methods=['get']) queryset = Adventure.objects.none()
def featured(self, request):
featured_adventures = Adventure.objects.filter( for adventure_type in types:
type='featured', is_public=True, trip=None) if adventure_type in ['visited', 'planned']:
serializer = self.get_serializer(featured_adventures, many=True) queryset |= Adventure.objects.filter(
type=adventure_type, user_id=request.user.id, trip=None)
elif adventure_type == 'featured':
queryset |= Adventure.objects.filter(
type='featured', is_public=True, trip=None)
return self.paginate_and_respond(queryset, request)
def paginate_and_respond(self, queryset, request):
paginator = self.pagination_class()
page = paginator.paginate_queryset(queryset, request)
if page is not None:
serializer = self.get_serializer(page, many=True)
return paginator.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) return Response(serializer.data)
class TripViewSet(viewsets.ModelViewSet): class TripViewSet(viewsets.ModelViewSet):
@ -57,11 +79,12 @@ class TripViewSet(viewsets.ModelViewSet):
def perform_create(self, serializer): def perform_create(self, serializer):
serializer.save(user_id=self.request.user) serializer.save(user_id=self.request.user)
@action(detail=False, methods=['get'])
@action(detail=False, methods=['get']) @action(detail=False, methods=['get'])
def visited(self, request): def visited(self, request):
trips = self.get_queryset().filter(type='visited', user_id=request.user.id) visited_adventures = Adventure.objects.filter(
serializer = self.get_serializer(trips, many=True) type='visited', user_id=request.user.id, trip=None)
return Response(serializer.data) return self.get_paginated_response(visited_adventures)
@action(detail=False, methods=['get']) @action(detail=False, methods=['get'])
def planned(self, request): def planned(self, request):

View file

@ -2,11 +2,11 @@ version: "3.9"
services: services:
web: web:
#build: ./frontend/ build: ./frontend/
image: ghcr.io/seanmorley15/adventurelog-frontend:latest #image: ghcr.io/seanmorley15/adventurelog-frontend:latest
environment: environment:
- PUBLIC_SERVER_URL=http://server:8000 - PUBLIC_SERVER_URL=http://server:8000
- ORIGIN=http://localhost:8080 - ORIGIN=http://10.0.0.92:8080
- BODY_SIZE_LIMIT=Infinity - BODY_SIZE_LIMIT=Infinity
ports: ports:
- "8080:3000" - "8080:3000"
@ -23,8 +23,8 @@ services:
- postgres_data:/var/lib/postgresql/data/ - postgres_data:/var/lib/postgresql/data/
server: server:
#build: ./backend/ build: ./backend/
image: ghcr.io/seanmorley15/adventurelog-backend:latest #image: ghcr.io/seanmorley15/adventurelog-backend:latest
environment: environment:
- PGHOST=db - PGHOST=db
- PGDATABASE=database - PGDATABASE=database
@ -34,7 +34,7 @@ services:
- DJANGO_ADMIN_USERNAME=admin - DJANGO_ADMIN_USERNAME=admin
- DJANGO_ADMIN_PASSWORD=admin - DJANGO_ADMIN_PASSWORD=admin
- DJANGO_ADMIN_EMAIL=admin@example.com - DJANGO_ADMIN_EMAIL=admin@example.com
- PUBLIC_URL='http://127.0.0.1:81' - PUBLIC_URL='http://10.0.92:81'
- CSRF_TRUSTED_ORIGINS=https://api.adventurelog.app,https://adventurelog.app - CSRF_TRUSTED_ORIGINS=https://api.adventurelog.app,https://adventurelog.app
- DEBUG=False - DEBUG=False
ports: ports:

View file

@ -34,8 +34,8 @@ export const actions: Actions = {
} }
}); });
if (res.ok) { if (res.ok) {
cookies.delete('auth', { path: '/' }); cookies.delete('auth', { path: '/', secure: false });
cookies.delete('refresh', { path: '/' }); cookies.delete('refresh', { path: '/', secure: false });
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
return redirect(302, '/'); return redirect(302, '/');

View file

@ -13,32 +13,37 @@ export const load = (async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let next = null;
let previous = null;
let count = 0;
let adventures: Adventure[] = []; let adventures: Adventure[] = [];
let visitedFetch = await fetch(`${serverEndpoint}/api/adventures/visited/`, { let initialFetch = await fetch(
headers: { `${serverEndpoint}/api/adventures/filtered?types=visited,planned`,
Cookie: `${event.cookies.get('auth')}` {
headers: {
Cookie: `${event.cookies.get('auth')}`
}
} }
}); );
if (!visitedFetch.ok) { if (!initialFetch.ok) {
console.error('Failed to fetch visited adventures'); console.error('Failed to fetch visited adventures');
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let visited = (await visitedFetch.json()) as Adventure[]; let res = await initialFetch.json();
let visited = res.results as Adventure[];
next = res.next;
previous = res.previous;
count = res.count;
adventures = [...adventures, ...visited]; adventures = [...adventures, ...visited];
} }
let plannedFetch = await fetch(`${serverEndpoint}/api/adventures/planned/`, {
headers: { return {
Cookie: `${event.cookies.get('auth')}` props: {
adventures,
next,
previous
} }
}); };
if (!plannedFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let planned = (await plannedFetch.json()) as Adventure[];
adventures = [...adventures, ...planned];
}
return { adventures } as { adventures: Adventure[] };
} }
}) satisfies PageServerLoad; }) satisfies PageServerLoad;
@ -366,49 +371,55 @@ export const actions: Actions = {
}; };
} }
let filterString = '';
if (visited) { if (visited) {
let visitedFetch = await fetch(`${serverEndpoint}/api/adventures/visited/`, { filterString += 'visited';
headers: {
Cookie: `${event.cookies.get('auth')}`
}
});
if (!visitedFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let visited = (await visitedFetch.json()) as Adventure[];
adventures = [...adventures, ...visited];
}
} }
if (planned) { if (planned) {
let plannedFetch = await fetch(`${serverEndpoint}/api/adventures/planned/`, { if (filterString) {
headers: { filterString += ',';
Cookie: `${event.cookies.get('auth')}`
}
});
if (!plannedFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let planned = (await plannedFetch.json()) as Adventure[];
adventures = [...adventures, ...planned];
} }
filterString += 'planned';
} }
if (featured) { if (featured) {
let featuredFetch = await fetch(`${serverEndpoint}/api/adventures/featured/`, { if (filterString) {
filterString += ',';
}
filterString += 'featured';
}
if (!filterString) {
filterString = '';
}
let next = null;
let previous = null;
let count = 0;
let visitedFetch = await fetch(
`${serverEndpoint}/api/adventures/filtered?types=${filterString}`,
{
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `${event.cookies.get('auth')}`
} }
});
if (!featuredFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let featured = (await featuredFetch.json()) as Adventure[];
adventures = [...adventures, ...featured];
} }
);
if (!visitedFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let res = await visitedFetch.json();
let visited = res.results as Adventure[];
next = res.next;
previous = res.previous;
count = res.count;
adventures = [...adventures, ...visited];
} }
// console.log(adventures);
return adventures as Adventure[]; return {
adventures,
next,
previous,
count
};
} }
}; };

View file

@ -11,13 +11,34 @@
export let data: any; export let data: any;
console.log(data); console.log(data);
let adventures: Adventure[] = data.adventures || []; let adventures: Adventure[] = data.props.adventures || [];
let currentSort = { attribute: 'name', order: 'asc' }; let currentSort = { attribute: 'name', order: 'asc' };
let isShowingCreateModal: boolean = false; let isShowingCreateModal: boolean = false;
let newType: string = ''; let newType: string = '';
let next: string | null = null;
let previous: string | null = null;
let count = 0;
async function changePage(direction: string) {
let url: string = '';
if (direction === 'next' && next) {
url = next;
} else if (direction === 'previous' && previous) {
url = previous;
} else {
return;
}
let res = await fetch(url);
let result = await res.json();
adventures = result.results as Adventure[];
next = result.next;
previous = result.previous;
count = result.count;
}
function handleSubmit() { function handleSubmit() {
return async ({ result, update }: any) => { return async ({ result, update }: any) => {
// First, call the update function with reset: false // First, call the update function with reset: false
@ -27,8 +48,11 @@
if (result.type === 'success') { if (result.type === 'success') {
if (result.data) { if (result.data) {
// console.log(result.data); // console.log(result.data);
adventures = result.data as Adventure[]; adventures = result.data.adventures as Adventure[];
sort(currentSort); next = result.data.next;
previous = result.data.previous;
count = result.data.count;
// sort(currentSort);
} }
} }
}; };
@ -39,9 +63,9 @@
currentSort.order = order; currentSort.order = order;
if (attribute === 'name') { if (attribute === 'name') {
if (order === 'asc') { if (order === 'asc') {
adventures = adventures.sort((a, b) => a.name.localeCompare(b.name));
} else {
adventures = adventures.sort((a, b) => b.name.localeCompare(a.name)); adventures = adventures.sort((a, b) => b.name.localeCompare(a.name));
} else {
adventures = adventures.sort((a, b) => a.name.localeCompare(b.name));
} }
} }
} }
@ -140,6 +164,7 @@
<div class="drawer-content"> <div class="drawer-content">
<!-- Page content --> <!-- Page content -->
<h1 class="text-center font-bold text-4xl mb-6">My Adventures</h1> <h1 class="text-center font-bold text-4xl mb-6">My Adventures</h1>
<p class="text-center">This search returned {count} results.</p>
{#if adventures.length === 0} {#if adventures.length === 0}
<NotFound /> <NotFound />
{/if} {/if}
@ -160,6 +185,17 @@
/> />
{/each} {/each}
</div> </div>
<div class="join grid grid-cols-2">
{#if previous}
<button class="join-item btn btn-outline" on:click={() => changePage('previous')}
>Previous page</button
>
{/if}
{#if next}
<button class="join-item btn btn-outline" on:click={() => changePage('next')}>Next</button
>
{/if}
</div>
</div> </div>
</div> </div>
<div class="drawer-side"> <div class="drawer-side">

View file

@ -60,13 +60,15 @@ export const actions: Actions = {
httpOnly: true, httpOnly: true,
sameSite: 'lax', sameSite: 'lax',
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
path: '/' path: '/',
secure: false
}); });
event.cookies.set('refresh', refreshToken, { event.cookies.set('refresh', refreshToken, {
httpOnly: true, httpOnly: true,
sameSite: 'lax', sameSite: 'lax',
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year
path: '/' path: '/',
secure: false
}); });
return redirect(302, '/'); return redirect(302, '/');