Files
old-web/app/helpers/fetchWrapper.js

59 lines
1.7 KiB
JavaScript
Raw Normal View History

const nodeFetch = require("node-fetch");
2020-09-15 01:27:20 -07:00
const AbortController = require('abort-controller');
2020-10-21 06:16:35 +02:00
const FetchCache = require('@sozialhelden/fetch-cache').default;
console.log("Fc ", FetchCache)
2020-02-22 22:15:27 +01:00
const {
USER_AGENT,
USE_SCRAPER_API,
SCRAPER_API_KEY,
2020-09-16 06:16:49 -07:00
SCRAPER_API_BASE_URL,
NODE_FETCH_TIMEOUT_MS
2020-02-22 22:15:27 +01:00
} = require("../config/appConfig");
2020-09-10 18:30:14 +02:00
const timeout = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
2020-09-10 18:08:24 +02:00
}
2020-10-21 06:16:35 +02:00
const fetchCache = new FetchCache({
fetch: nodeFetch,
cacheOptions: {
// Don't save more than 100 responses in the cache. Allows infinite responses by default
maximalItemCount: 10000,
// When should the cache evict responses when its full?
evictExceedingItemsBy: 'age', // Valid values: 'lru' or 'age'
2020-10-21 10:49:22 +02:00
defaultTTL: 6 * 60 * 60 * 1000 // 6 hours
2020-10-21 06:16:35 +02:00
// ...see https://github.com/sozialhelden/hamster-cache for all possible options
},
});
const fetch = async (url, options = {}, useCache = true) => {
2020-09-15 01:27:20 -07:00
const controller = new AbortController();
const newOptions = Object.assign({}, options);
if (!newOptions["headers"]) {
newOptions["headers"] = {};
}
2020-09-15 01:27:20 -07:00
newOptions.signal = controller.signal;
2020-09-10 17:57:21 +02:00
// newOptions["headers"]["User-Agent"] = USER_AGENT;
2020-09-10 17:34:39 +02:00
let urlToFetchThroughAPI = Buffer.from(url).toString('base64');
if (SCRAPER_API_BASE_URL.includes('scraperapi')) {
urlToFetchThroughAPI = url;
}
2020-02-23 23:11:21 +01:00
const urlAdaptedForScraping = USE_SCRAPER_API
2020-09-10 17:34:39 +02:00
? `${SCRAPER_API_BASE_URL}?api_key=${SCRAPER_API_KEY}&url=${urlToFetchThroughAPI}`
2020-02-22 22:15:27 +01:00
: url;
2020-10-21 06:16:35 +02:00
const result = useCache ? fetchCache.fetch(urlAdaptedForScraping, newOptions) : nodeFetch(urlAdaptedForScraping, newOptions);
2020-09-16 06:16:49 -07:00
const timeoutId = setTimeout(() => controller.abort(), NODE_FETCH_TIMEOUT_MS);
2020-09-15 01:27:20 -07:00
return result;
};
module.exports = fetch;