Skip to content

Commit

Permalink
refactor: logging, placemend of funcs and other small stuff, added JS…
Browse files Browse the repository at this point in the history
…R.IO (#365)
  • Loading branch information
aleksasiriski authored Jul 9, 2024
1 parent e9cad52 commit cbe9327
Show file tree
Hide file tree
Showing 21 changed files with 262 additions and 543 deletions.
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
engine-strict=true
@jsr:registry=https://npm.jsr.io
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"test:unit": "vitest"
},
"devDependencies": {
"@hearchco/sveltekit-adapter-aws": "github:hearchco/sveltekit-adapter-aws#v0.1.4",
"@hearchco/sveltekit-adapter-aws": "npm:@jsr/hearchco__sveltekit-adapter-aws@^0.1.10",
"@playwright/test": "^1.45.1",
"@sveltejs/adapter-node": "^5.2.0",
"@sveltejs/kit": "^2.5.18",
Expand All @@ -25,7 +25,7 @@
"eslint": "^9.6.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.41.0",
"globals": "^15.7.0",
"globals": "^15.8.0",
"postcss": "^8.4.39",
"prettier": "^3.3.2",
"prettier-plugin-svelte": "^3.2.5",
Expand Down
587 changes: 159 additions & 428 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions src/lib/components/results/general/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
/**
* @typedef {object} Props
* @property {boolean} javascript
* @property {boolean} browser
* @property {string} query
* @property {string} category
* @property {number} currentPage
* @property {ResultType[]} results
*/
/** @type {Props} */
let { javascript, query, category, currentPage, results } = $props();
let { browser, query, category, currentPage, results } = $props();
</script>

<div class="mx-auto pb-4 max-w-screen-sm">
Expand All @@ -27,7 +27,7 @@
</section>
</div>

{#if !javascript}
{#if !browser}
<Paginator {query} {category} {currentPage} />
{:else}
<InfiniteLoading {query} {category} {currentPage} bind:results />
Expand Down
8 changes: 4 additions & 4 deletions src/lib/components/results/images/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
/**
* @typedef {object} Props
* @property {boolean} javascript
* @property {boolean} browser
* @property {string} query
* @property {string} category
* @property {number} currentPage
Expand All @@ -15,11 +15,11 @@
*/
/** @type {Props} */
let { javascript, query, category, currentPage, results, imagePreview = $bindable() } = $props();
let { browser, query, category, currentPage, results, imagePreview = $bindable() } = $props();
</script>

<div class="px-4 py-8 w-full lg:flex">
<!-- preview on top when screen width <lg -->
<!-- Preview on top when screen width less than lg -->
{#if imagePreview}
<div
id="image-preview-sm"
Expand Down Expand Up @@ -52,7 +52,7 @@
{/if}
</div>

{#if !javascript}
{#if !browser}
<Paginator {query} {category} {currentPage} />
{:else}
<InfiniteLoading {query} {category} {currentPage} bind:results />
Expand Down
20 changes: 3 additions & 17 deletions src/lib/components/results/paginator/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,15 @@
const numberOfPages = 5;
const offset = $derived(currentPage > 3 ? currentPage - 3 : 0);
/**
* @param {number} index
* @returns {number}
*/
function calcPageNum(index) {
return index + offset + 1;
}
/**
* @param {number} index
* @returns {boolean}
*/
function selected(index) {
return currentPage === calcPageNum(index);
}
</script>

<form class="pb-5 flex flex-row justify-center" method="get" action="/search">
<input type="hidden" name="q" value={query} />
<input type="hidden" name="category" value={category} />
<!-- eslint-disable-next-line no-unused-vars -->
{#each { length: numberOfPages } as _, i}
<Number page={calcPageNum(i)} selected={selected(i)} />
{@const page = i + offset + 1}
{@const selected = currentPage === page}
<Number {page} {selected} />
{/each}
</form>
6 changes: 3 additions & 3 deletions src/lib/components/themetoggle/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@
</script>
<svelte:head>
<!-- prevent Chromium based browser from inverting the page -->
<!-- Prevent Chromium based browser from inverting the page. -->
<meta name="color-scheme" content="light" />
<!-- prevent Dark Reader from inverting the page -->
<!-- Prevent Dark Reader from inverting the page. -->
<meta name="darkreader-lock" />
<!-- initialize theme -->
<!-- Load theme before body starts rendering. -->
<script>
const selectedTheme = localStorage.getItem('theme') ?? 'system';
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
Expand Down
14 changes: 8 additions & 6 deletions src/lib/functions/api/additionalresults.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import { fetchResults } from './fetchresults';

/**
* Fetches additional results from the API and combines with the old results
* Fetches additional results from the API and combines with the old results.
* @param {ResultType[]} oldResults
* @param {URLSearchParams} params
* @returns {Promise<ResultType[]>}
*/
export async function fetchAdditionalResults(oldResults, params) {
const newResults = (await fetchResults(params)).results;
const resp = await fetchResults(params);
const newResults = resp.results;

// get the last rank from old results
// Get the last rank from old results.
const lastRank = oldResults[oldResults.length - 1].rank;

// make the new results start from the last rank of the old results
// Make the new results start from the last rank of the old results.
for (const result of newResults) {
result.rank += lastRank;
}

// combine the old results with the new results (removing duplicates)
// Combine the old results with the new results (removing duplicates).
const combinedResults = oldResults.concat(
newResults.filter(
(newResult) => !oldResults.some((oldResult) => oldResult.url === newResult.url)
)
);

// make all ranks consecutive (starting from the appended results, because the old results already have consecutive ranks)
// Make all ranks consecutive.
// Starting from the appended results, because the old results already have consecutive ranks.
for (let i = lastRank; i < combinedResults.length; i++) {
combinedResults[i].rank = i + 1;
}
Expand Down
8 changes: 4 additions & 4 deletions src/lib/functions/api/concatparams.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/**
* Concatenate search params
* @param {Record<string, string>} searchParamsMap - Array of search params
* @returns {URLSearchParams} - Concatenated search params
* Concatenate search params.
* @param {Record<string, string>} searchParamsMap - Array of search params.
* @returns {URLSearchParams} - Concatenated search params.
*/
export function concatSearchParams(searchParamsMap) {
// Convert search params map to array avoiding empty values
// Convert search params map to array avoiding empty values.
const searchParamsArray = Object.entries(searchParamsMap).map(([key, value]) =>
value !== '' ? `${key}=${value}` : ''
);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/functions/api/createurl.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';

/**
* Create an API URL
* Create an API URL.
* @param {string} [path]
* @param {URLSearchParams} [params]
* @returns {URL}
*/
export function createApiUrl(path, params) {
const apiUri = env.PUBLIC_API_URI;
if (!apiUri) {
// Internal Server Error
// Internal Server Error.
throw error(500, 'PUBLIC_API_URI env is not defined');
}

Expand Down
10 changes: 5 additions & 5 deletions src/lib/functions/api/fetchresults.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@ export async function fetchResults(params, fetcher = fetch) {
try {
apiUrl = createApiUrl('search', params);
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err.message}`);
}

/** @type {Response} */
let response;
try {
response = await fetcher(apiUrl, {
method: 'GET', // POST doesn't cache on CDN
method: 'GET', // POST doesn't cache on CDN.
headers: {
Accept: 'application/json',
'Accept-Encoding': 'gzip, deflate, br'
}
});
} catch (/** @type {any} */ err) {
// Bad Gateway
// Bad Gateway.
throw error(502, `Failed to fetch results: ${err.message}`);
}

Expand All @@ -36,12 +36,12 @@ export async function fetchResults(params, fetcher = fetch) {
try {
jsonResponse = await response.json();
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to parse results: ${err.message}`);
}

if ('message' in jsonResponse && 'value' in jsonResponse) {
// same as backend
// Same as backend.
throw error(response.status, `API error: ${jsonResponse.message}: ${jsonResponse.value}`);
}

Expand Down
8 changes: 4 additions & 4 deletions src/lib/functions/api/fetchsuggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ export async function fetchSuggestions(query, fetcher = fetch) {
try {
apiUrl = createApiUrl('suggestions', params);
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err.message}`);
}

/** @type {Response} */
let response;
try {
response = await fetcher(apiUrl, {
method: 'GET', // POST doesn't cache on CDN
method: 'GET', // POST doesn't cache on CDN.
headers: {
Accept: 'application/json',
'Accept-Encoding': 'gzip, deflate, br'
Expand All @@ -39,12 +39,12 @@ export async function fetchSuggestions(query, fetcher = fetch) {
try {
jsonResponse = await response.json();
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to parse suggestions: ${err.message}`);
}

if ('message' in jsonResponse && 'value' in jsonResponse) {
// same as backend
// Same as backend.
throw error(response.status, `API error: ${jsonResponse.message}: ${jsonResponse.value}`);
}

Expand Down
6 changes: 3 additions & 3 deletions src/lib/functions/api/fetchversion.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,22 @@ export async function fetchVersion(fetcher = fetch) {
try {
apiUrl = createApiUrl('versionz');
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err.message}`);
}

/** @type {Response} */
let response;
try {
response = await fetcher(apiUrl, {
method: 'GET', // POST doesn't cache on CDN
method: 'GET', // POST doesn't cache on CDN.
headers: {
Accept: 'text/plain',
'Accept-Encoding': 'gzip, deflate, br'
}
});
} catch (/** @type {any} */ err) {
// Bad Gateway
// Bad Gateway.
throw error(502, `Failed to fetch version: ${err.message}`);
}

Expand Down
13 changes: 8 additions & 5 deletions src/lib/functions/api/proxyimage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ import { error } from '@sveltejs/kit';
import { createApiUrl } from '$lib/functions/api/createurl';

/**
* Create a public API URL for the proxy image endpoint
* Create a public API URL for the proxy image endpoint.
* @param {string} url
* @param {string} hash
* @param {boolean} [favicon]
* @returns {string}
*/
export function proxyImageLink(url, hash, favicon = false) {
// must be done like this instead of concatSearchParams because URL musn't be encoded
// Must be done like this instead of concatSearchParams because URL musn't be encoded.
const params = new URLSearchParams();
// ordered alphabetically to increase cache hits

// Ordered alphabetically to increase cache hits.
params.set('hash', hash);
params.set('url', url);
params.set('favicon', favicon.toString());
Expand All @@ -21,15 +22,15 @@ export function proxyImageLink(url, hash, favicon = false) {
try {
apiUrl = createApiUrl('proxy', params);
} catch (/** @type {any} */ err) {
// Internal Server Error
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err.message}`);
}

return apiUrl.toString();
}

/**
* Create a public API URL for the proxy favicon image endpoint
* Create a public API URL for the proxy favicon image endpoint.
* @param {string} url
* @param {string} hash
* @returns {string}
Expand All @@ -38,9 +39,11 @@ export function proxyFaviconLink(url, hash) {
const uriPattern = '^(http(s?))(://)([^/]+)';
const uriRegex = new RegExp(uriPattern);
const uriMatch = url.match(uriRegex);

if (!uriMatch || uriMatch.length == 0) {
throw error(400, 'Invalid URL');
}

const uri = uriMatch[0];
return proxyImageLink(uri, hash, true);
}
4 changes: 2 additions & 2 deletions src/lib/functions/sleep/sleep.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @param {number} duration - The duration to sleep in milliseconds
* @returns {Promise<void>} - A promise that resolves after the duration
* @param {number} duration - The duration to sleep in milliseconds.
* @returns {Promise<void>} - A promise that resolves after the duration.
*/
export async function sleep(duration) {
await new Promise((r) => setTimeout(r, duration));
Expand Down
4 changes: 0 additions & 4 deletions src/lib/types/search/category.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,15 @@ export const CategoryEnum = {
export function toCategoryType(category) {
switch (category) {
case 'general':
return CategoryEnum.GENERAL;
case 'normal':
return CategoryEnum.GENERAL;
case 'images':
return CategoryEnum.IMAGES;
case 'image':
return CategoryEnum.IMAGES;
case 'science':
return CategoryEnum.SCIENCE;
case 'sci':
return CategoryEnum.SCIENCE;
case 'thorough':
return CategoryEnum.THOROUGH;
case 'slow':
return CategoryEnum.THOROUGH;
default:
Expand Down
Loading

0 comments on commit cbe9327

Please sign in to comment.