Skip to content

Commit

Permalink
Merge pull request #317 from hearchco/as/fix/timing
Browse files Browse the repository at this point in the history
fix: switch to universal page load and use only scraped timing
  • Loading branch information
aleksasiriski authored Jun 20, 2024
2 parents d798b3e + 852f314 commit cd77b65
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 121 deletions.
8 changes: 1 addition & 7 deletions src/hooks.server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@ import { error } from '@sveltejs/kit';
import { env as privateEnv } from '$env/dynamic/private';
import { env as publicEnv } from '$env/dynamic/public';

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
console.log('Origin:', event.url.origin);
return resolve(event);
}

/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
const privateApiUri = privateEnv.API_URI;
Expand All @@ -23,7 +17,7 @@ export async function handleFetch({ request, fetch }) {
}

if (request.url.startsWith(publicApiUri)) {
// clone the original request, but change the URL
// Clone the original request, but change the URL
request = new Request(request.url.replace(publicApiUri, privateApiUri), request);
}

Expand Down
9 changes: 4 additions & 5 deletions src/lib/components/header/stats.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
/**
* @typedef {object} Props
* @property {number} numOfResults
* @property {TimingType} timing
* @property {number} duration
*/
/** @type {Props} */
let { numOfResults, timing } = $props();
const timingFetchString = $derived((timing.fetch / 1000).toFixed(2));
const timingScrapeString = $derived((timing.scrape / 1000).toFixed(2));
let { numOfResults, duration } = $props();
const durationString = $derived((duration / 1000).toFixed(2));
</script>

<div id="stats" class="mx-auto px-2 pt-2 max-w-screen-sm">
<p class="text-sm text-neutral-800 dark:text-neutral-400">
Hearched {numOfResults} results in {timingFetchString}s (scraped in {timingScrapeString}s) 🐹
Hearched {numOfResults} results in {durationString}s 🐹
</p>
</div>
6 changes: 0 additions & 6 deletions src/lib/types/search/timing.js

This file was deleted.

88 changes: 81 additions & 7 deletions src/routes/search/+page.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,88 @@
import { browser } from '$app/environment';
import { error } from '@sveltejs/kit';

import { getCategoryFromQuery, getQueryWithoutCategory } from '$lib/functions/query/category';
import { concatSearchParams } from '$lib/functions/api/concatparams';
import { fetchResults } from '$lib/functions/api/fetchresults';

import { CategoryEnum, toCategoryType } from '$lib/types/search/category';

/**
* Get category from URL or query
* @param {string} query - Query from URL
* @param {URLSearchParams} params - Parameters
* @returns {string} - Category
* @throws {Error} - If category is invalid
*/
function getCategory(query, params) {
const categoryFromQuery = getCategoryFromQuery(query);
const categoryParam = params.get('category') ?? '';
const category =
categoryFromQuery !== ''
? toCategoryType(categoryFromQuery)
: categoryParam !== ''
? toCategoryType(categoryParam)
: CategoryEnum.GENERAL;

// Check if category is valid
if (!category) {
// Bad Request
throw error(400, "Invalid 'category' parameter in URL or query");
}

return category;
}

/** @type {import('./$types').PageLoad} */
export async function load({ data }) {
export async function load({ url, fetch }) {
// Get query, current page, and max pages from URL
const query = url.searchParams.get('q') ?? '';
const currentPage = parseInt(url.searchParams.get('start') ?? '1', 10);
const maxPages = parseInt(url.searchParams.get('pages') ?? '1', 10);

// Validate query, current page, and max pages
if (query === '') {
// Bad Request
throw error(400, "Missing 'q' parameter");
}
if (isNaN(currentPage) || currentPage <= 0) {
// Bad Request
throw error(400, "Invalid 'start' parameter");
}
if (isNaN(maxPages) || maxPages <= 0) {
// Bad Request
throw error(400, "Invalid 'pages' parameter");
}

// Get category from URL or query (query takes precedence)
const category = getCategory(query, url.searchParams);

// Remove category from query if it exists
const queryWithoutCategory = getQueryWithoutCategory(query);
if (queryWithoutCategory === '') {
// Bad Request
throw error(400, "Only category specified in 'q' parameter");
}

// Concatenate search params
const newSearchParams = concatSearchParams({
q: queryWithoutCategory,
category: category !== CategoryEnum.GENERAL ? category : '',
start: currentPage !== 1 ? currentPage.toString() : '',
pages: maxPages !== 1 ? maxPages.toString() : ''
});

// Fetch results
const resp = await fetchResults(newSearchParams, fetch);

return {
browser: browser,
query: data.query,
currentPage: data.currentPage,
maxPages: data.maxPages,
category: data.category,
results: data.results,
timing: data.timing
apiVersion: resp.version,
query: queryWithoutCategory,
currentPage: currentPage,
maxPages: maxPages,
category: category,
results: resp.results,
duration: resp.duration
};
}
94 changes: 0 additions & 94 deletions src/routes/search/+page.server.js

This file was deleted.

4 changes: 2 additions & 2 deletions src/routes/search/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
// const maxPages = $derived(data.maxPages);
const category = $derived(data.category);
const results = $derived(data.results);
const timing = $derived(data.timing);
const duration = $derived(data.duration);
/** @type {ResultType | undefined} */
let imagePreview = $state(undefined);
Expand All @@ -39,7 +39,7 @@

<Header {query} {category} />
{#if results.length !== 0}
<Stats numOfResults={results.length} {timing} />
<Stats numOfResults={results.length} {duration} />
{/if}

{#if results.length === 0}
Expand Down

0 comments on commit cd77b65

Please sign in to comment.