1. /**
  2. * Paginates results from a URL list with a timeout for temporary use.
  3. * @param {string} urlListUrl - The URL to fetch the list of URLs from.
  4. * @param {number} pageSize - The number of URLs to fetch per page.
  5. * @param {number} timeoutMs - The timeout in milliseconds for each request.
  6. * @returns {Promise<Array<string>>} - A promise that resolves to an array of URLs, or rejects on error.
  7. */
  8. async function paginateUrls(urlListUrl, pageSize, timeoutMs) {
  9. try {
  10. const response = await fetch(urlListUrl);
  11. if (!response.ok) {
  12. throw new Error(`HTTP error! Status: ${response.status}`);
  13. }
  14. const data = await response.json(); // Assuming the response is JSON
  15. if (!Array.isArray(data)) {
  16. throw new Error("Expected a JSON array of URLs.");
  17. }
  18. const allUrls = data;
  19. const totalItems = allUrls.length;
  20. const totalPages = Math.ceil(totalItems / pageSize);
  21. async function getPage(pageNumber) {
  22. const start = (pageNumber - 1) * pageSize;
  23. const end = start + pageSize;
  24. const pageUrls = allUrls.slice(start, end);
  25. // Simulate a timeout for each request. In a real-world scenario,
  26. // this would be handled by the underlying fetch API.
  27. await new Promise(resolve => setTimeout(resolve, timeoutMs));
  28. return pageUrls;
  29. }
  30. const allPages = [];
  31. for (let page = 1; page <= totalPages; page++) {
  32. allPages.push(getPage(page));
  33. }
  34. return allPages.flat(); // Flatten the array of arrays into a single array.
  35. } catch (error) {
  36. console.error("Error paginating URLs:", error);
  37. throw error; // Re-throw the error for handling by the caller.
  38. }
  39. }
  40. export default paginateUrls;

Add your comment