nepse-api-helper
Version:
a wrapper to use nepse api easily since they set up weird restrictions
49 lines (48 loc) • 1.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchWithTimeout = fetchWithTimeout;
exports.fetchWithRetry = fetchWithRetry;
exports.createHeaders = createHeaders;
const constants_1 = require("./constants");
async function fetchWithTimeout(url, options, timeout = constants_1.REQUEST_TIMEOUT_MS) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal
});
return response;
}
finally {
clearTimeout(id);
}
}
async function fetchWithRetry(url, options, retries = constants_1.MAX_RETRIES, delay = constants_1.RETRY_DELAY_MS) {
try {
return await fetchWithTimeout(url, options);
}
catch (error) {
if (retries <= 0) {
throw error;
}
// Only retry on network errors or timeouts
if (error instanceof TypeError || error instanceof DOMException) {
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2);
}
throw error;
}
}
function createHeaders(token) {
return {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Referer": `${constants_1.BASE_URL}/`,
"Authorization": `Salter ${token}`,
"Content-Type": "application/json"
};
}