Skip to content

Commit

Permalink
Merge pull request #33 from tminaorg/double-api-call
Browse files Browse the repository at this point in the history
fix: Remove double api call (on SSR and CSR)
  • Loading branch information
aleksasiriski authored Nov 10, 2023
2 parents f5fa445 + c2e56f1 commit 46fe719
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/routes/healthz/api/private/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const csr = false;

import type { PageServerLoad } from './$types';
import { env } from '$env/dynamic/private';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ fetch }) => {
const apiUrl = `${env.API_URL}/healthz`;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/healthz/api/public/+page.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const ssr = false;

import type { PageLoad } from './$types';
import { env } from '$env/dynamic/public';
import type { PageLoad } from './$types';

export const load: PageLoad = async ({ fetch }) => {
const apiUrl = `${env.PUBLIC_API_URL}/healthz`;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/search/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

<div class="sm:mx-auto mb-4 max-w-screen-sm">
<div id="result-list" class="mx-2 my-4 max-w-fit overflow-clip">
{#each data.results as result (result.URL)}
{#each data.results as result}
<article id="result-{result.Rank}">
<a id="link" href={result.URL} class="dark:text-white" rel="noreferrer">{result.URL}</a>
<h1 id="title" class="brzaguza-text-blue hover:brzaguza-text-pink text-xl hover:underline">
Expand Down
18 changes: 13 additions & 5 deletions src/routes/search/+page.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { PageLoad } from './$types';
import { env } from '$env/dynamic/public';
import { browser } from '$app/environment';
import type { PageLoad } from './$types';

export const load: PageLoad = async ({ fetch, url }) => {
const q = url.searchParams.get('q');
Expand All @@ -17,13 +17,21 @@ export const load: PageLoad = async ({ fetch, url }) => {
} else {
apiUri = env.PUBLIC_API_URL_CSR;
}

const apiUrl = `${apiUri}/search?${url.searchParams}`;
const response = await fetch(apiUrl);
const results = await response.json();

// it's important to use the included fetch so that the fetch is not run again in the browser
const resultsP = new Promise((resolve, reject) => {
fetch(apiUrl)
.then((res) => {
resolve(res.json());
})
.catch((err) => {
reject(err);
});
});

return {
query: q,
results: results
results: browser ? resultsP : await resultsP
};
};

0 comments on commit 46fe719

Please sign in to comment.