save matches pagination cursor in url

This commit is contained in:
Ilion Beyst 2022-08-11 23:06:53 +02:00
parent 406c726601
commit 7c4314ae23

View file

@ -3,12 +3,22 @@
const PAGE_SIZE = "50"; const PAGE_SIZE = "50";
export async function load({ fetch }) { export async function load({ url, fetch }) {
try { try {
const apiClient = new ApiClient(fetch); const apiClient = new ApiClient(fetch);
const matches = await apiClient.get("/api/matches", {
let query = {
count: PAGE_SIZE, count: PAGE_SIZE,
}); before: url.searchParams.get("before"),
after: url.searchParams.get("after"),
};
let matches = await apiClient.get("/api/matches", removeUndefined(query));
// TODO: should this be done client-side?
if (query["after"]) {
matches = matches.reverse();
}
return { return {
props: { props: {
@ -22,28 +32,30 @@
}; };
} }
} }
function removeUndefined(obj: Record<string, string>): Record<string, string> {
Object.keys(obj).forEach((key) => {
if (obj[key] === undefined || obj[key] === null) {
delete obj[key];
}
});
return obj;
}
</script> </script>
<script lang="ts"> <script lang="ts">
import { goto } from "$app/navigation";
import MatchList from "$lib/components/matches/MatchList.svelte"; import MatchList from "$lib/components/matches/MatchList.svelte";
export let matches: object[]; export let matches: object[];
let loading = false;
async function loadNewer() { async function loadNewer() {
if (matches.length == 0) { if (matches.length == 0) {
return; return;
} }
const firstTimestamp = matches[0]["timestamp"]; const firstTimestamp = matches[0]["timestamp"];
const apiClient = new ApiClient(); goto(`?after=${firstTimestamp}`);
const reversedNewPage = await apiClient.get("/api/matches", {
count: PAGE_SIZE,
after: firstTimestamp,
});
if (reversedNewPage.length > 0) {
matches = reversedNewPage.reverse();
}
} }
async function loadOlder() { async function loadOlder() {
@ -51,14 +63,7 @@
return; return;
} }
const lastTimestamp = matches[matches.length - 1]["timestamp"]; const lastTimestamp = matches[matches.length - 1]["timestamp"];
const apiClient = new ApiClient(); goto(`?before=${lastTimestamp}`);
const newPage = await apiClient.get("/api/matches", {
count: PAGE_SIZE,
before: lastTimestamp,
});
if (newPage.length > 0) {
matches = newPage;
}
} }
</script> </script>