Skip to content

Enhance search.js with Error Handling and Input Validation #10179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions src/main/js/api/search.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,35 @@
/**
* @param {string} searchTerm
* Performs a search query using the provided search term.
* @param {string} searchTerm - The term to search for.
* @returns {Promise<Response>} - A promise resolving to the fetch response.
* @throws {Error} - Throws an error if the search URL is missing or invalid.
*/
function search(searchTerm) {
const address = document.getElementById("button-open-command-palette").dataset
.searchUrl;
return fetch(`${address}?query=${encodeURIComponent(searchTerm)}`);
if (typeof searchTerm !== "string" || searchTerm.trim() === "") {
throw new Error("Invalid search term. It must be a non-empty string.");
}

const buttonElement = document.getElementById("button-open-command-palette");
const address = buttonElement?.dataset?.searchUrl;

if (!address) {
throw new Error("Search URL is missing. Ensure the data-search-url attribute is set.");
}

const queryUrl = `${address}?query=${encodeURIComponent(searchTerm)}`;

return fetch(queryUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`Search failed with status: ${response.status}`);
}
return response;
})
.catch((error) => {
console.error("Error performing search:", error);
throw error;
});
}

export default { search: search };
export default { search };