UNPKG

fastcomments-react-native-sdk

Version:

React Native FastComments Components. Add live commenting to any React Native application.

60 lines (59 loc) 2.09 kB
export async function makeRequest({ apiHost, method, url, body, attemptsRemaining }) { // console.log('FastComments request', method, url); if (attemptsRemaining === undefined) { attemptsRemaining = 2; } const headers = { 'Accept': 'application/json', }; if (method === 'POST' || method === 'PUT' || method === 'DELETE') { headers['Content-type'] = 'application/json'; } const fullURL = apiHost + url; try { const result = await fetch(fullURL, { method, headers, credentials: 'include', body: body ? JSON.stringify(body) : undefined }); if (result.status !== 200 && result.status !== 401 && result.status !== 422 && result.status !== 429) { if (result.status !== 400 && attemptsRemaining > 0 && method === 'GET') { // 400 bad request is not retryable return new Promise((resolve, reject) => { setTimeout(async function () { attemptsRemaining--; try { resolve(await makeRequest({ apiHost, method, url, body, attemptsRemaining })); } catch (e) { reject(e); } }, 1500 * Math.random()); }); } else { return Promise.reject(result); } } else { return await result.json(); } } catch (e) { return Promise.reject(e); } } export function createURLQueryString(obj) { let result = []; for (const key in obj) { const value = obj[key]; if (value !== undefined) { // @ts-ignore result.push(key + '=' + encodeURIComponent(value)); } } return '?' + result.join('&'); } export function getAPIHost(config) { return config.apiHost ? config.apiHost : (config.region === 'eu' ? 'https://eu.fastcomments.com' : 'https://fastcomments.com'); }