aretherecookies-mobile/js/apis/FetchApi.js
2020-03-29 19:47:33 +00:00

45 lines
882 B
JavaScript

// @flow
import { BASE_URL } from '../constants/AppConstants';
import AuthManager from '../AuthManager';
export const fetchRequest = async ({
endpoint,
method,
headers = {},
body,
}: {
endpoint: string,
method: string,
headers?: Object,
body?: Object,
}) => {
const res = await fetch(`http://${BASE_URL}${endpoint}`, {
method,
headers: {
'Content-Type': 'application/json',
...AuthManager.getAuthHeader(),
...headers,
},
...(body ? { body: JSON.stringify(body) } : {}),
});
if (res.status === 401) {
AuthManager.deauthenticate();
}
if (!res.ok) {
throw new Error(await res.text());
}
return res.json();
};
export const fetchRequestBinary = async ({ endpoint, body }: { endpoint: string, body: any }) => {
return fetch(`http://${BASE_URL}${endpoint}`, {
method: 'POST',
headers: {
...AuthManager.getAuthHeader(),
},
body,
});
};