From 7c4314ae23c3021af1d17e76e582e2f03b507838 Mon Sep 17 00:00:00 2001
From: Ilion Beyst <ilion.beyst@gmail.com>
Date: Thu, 11 Aug 2022 23:06:53 +0200
Subject: save matches pagination cursor in url

---
 web/pw-server/src/routes/matches/index.svelte | 47 +++++++++++++++------------
 1 file changed, 26 insertions(+), 21 deletions(-)

(limited to 'web/pw-server/src/routes/matches/index.svelte')

diff --git a/web/pw-server/src/routes/matches/index.svelte b/web/pw-server/src/routes/matches/index.svelte
index c6eca50..95e653f 100644
--- a/web/pw-server/src/routes/matches/index.svelte
+++ b/web/pw-server/src/routes/matches/index.svelte
@@ -3,12 +3,22 @@
 
   const PAGE_SIZE = "50";
 
-  export async function load({ fetch }) {
+  export async function load({ url, fetch }) {
     try {
       const apiClient = new ApiClient(fetch);
-      const matches = await apiClient.get("/api/matches", {
+
+      let query = {
         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 {
         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 lang="ts">
+  import { goto } from "$app/navigation";
+
   import MatchList from "$lib/components/matches/MatchList.svelte";
 
   export let matches: object[];
-  let loading = false;
 
   async function loadNewer() {
     if (matches.length == 0) {
       return;
     }
     const firstTimestamp = matches[0]["timestamp"];
-    const apiClient = new ApiClient();
-    const reversedNewPage = await apiClient.get("/api/matches", {
-      count: PAGE_SIZE,
-      after: firstTimestamp,
-    });
-
-    if (reversedNewPage.length > 0) {
-      matches = reversedNewPage.reverse();
-    }
+    goto(`?after=${firstTimestamp}`);
   }
 
   async function loadOlder() {
@@ -51,14 +63,7 @@
       return;
     }
     const lastTimestamp = matches[matches.length - 1]["timestamp"];
-    const apiClient = new ApiClient();
-    const newPage = await apiClient.get("/api/matches", {
-      count: PAGE_SIZE,
-      before: lastTimestamp,
-    });
-    if (newPage.length > 0) {
-      matches = newPage;
-    }
+    goto(`?before=${lastTimestamp}`);
   }
 </script>
 
-- 
cgit v1.2.3

