UNPKG

fetchbee

Version:

A lightweight JS library to simplify all kinds of API calls.

51 lines (40 loc) 1.14 kB
async function fetchWithSearch(baseUrl, searchTerm, authToken, params = {}) { // Basic validation if (!baseUrl || typeof baseUrl !== "string") { console.warn("Invalid or missing baseUrl."); return null; } try { // Construct query parameters const queryParams = new URLSearchParams(); if (searchTerm) { queryParams.set("searchItem", searchTerm); } if (params && typeof params === "object") { for (const [key, value] of Object.entries(params)) { if (value != null) { queryParams.set(key, value); } } } const url = `${baseUrl}?${queryParams.toString()}`; // Build headers conditionally const headers = { 'Content-Type': 'application/json', }; if (authToken) { headers['Authorization'] = `Bearer ${authToken}`; } const response = await fetch(url, { method: 'GET', headers }); if (!response.ok) { throw new Error(`HTTP error ${response.status}`); } return await response.json(); } catch (error) { console.error("Fetch error:", error.message); return null; } }