fastcomments-sdk
Version:
FastComments API Client - A SDK for interacting with the FastComments API
68 lines • 2.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createURLQueryString = createURLQueryString;
exports.isAPIError = isAPIError;
exports.debounce = debounce;
exports.makeRequest = makeRequest;
function createURLQueryString(obj) {
const result = [];
for (const key in obj) {
const value = obj[key];
if (value) {
result.push(key + '=' + encodeURIComponent(obj[key]));
}
}
return '?' + result.join('&');
}
function isAPIError(obj) {
return obj && typeof obj === 'object' && 'status' in obj && obj.status === 'failed';
}
const debouncers = {};
function debounce(name, fn, delay = 300) {
if (debouncers[name]) {
clearTimeout(debouncers[name]);
}
debouncers[name] = setTimeout(async () => {
try {
await fn();
}
finally {
delete debouncers[name];
}
}, delay);
}
async function makeRequest(config, method, originalUrl, body, attemptsRemaining = 2) {
const url = (config.apiHost || 'https://fastcomments.com') + originalUrl;
try {
const response = await fetch(url, {
method,
body: body ? JSON.stringify(body) : undefined,
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
if (response.status !== 400 && attemptsRemaining > 0 && method === 'GET') {
await new Promise(resolve => setTimeout(resolve, 1500 * Math.random()));
return makeRequest(config, method, originalUrl, body, attemptsRemaining - 1);
}
else {
throw errorData;
}
}
return await response.json();
}
catch (error) {
if (attemptsRemaining > 0 && method === 'GET' && !error.status) {
await new Promise(resolve => setTimeout(resolve, 1500 * Math.random()));
return makeRequest(config, method, originalUrl, body, attemptsRemaining - 1);
}
else {
throw error;
}
}
}
//# sourceMappingURL=utils.js.map