You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.2 KiB
57 lines
1.2 KiB
import store from "../Reducers";
|
|
import {verificationFailedEvent} from "../Reducers/authReducer";
|
|
|
|
const PREFIX = "/api";
|
|
|
|
const dispatch = store.dispatch;
|
|
|
|
function formatUrl(url, params = {}) {
|
|
const urlWithPrefix = PREFIX + url;
|
|
|
|
const queryString =
|
|
Object
|
|
.keys(params)
|
|
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
|
|
|
|
if (queryString.length > 0) {
|
|
return urlWithPrefix + "?" + queryString;
|
|
}
|
|
|
|
return urlWithPrefix;
|
|
}
|
|
|
|
/**
|
|
* @param {Response} res
|
|
*/
|
|
function authCheck(res) {
|
|
if (res.ok) {
|
|
return Promise.resolve(res.json());
|
|
} else {
|
|
if (res.status === 403) {
|
|
dispatch(verificationFailedEvent());
|
|
|
|
// Allow the promise to sort of fizzle out
|
|
return Promise.resolve(null);
|
|
}
|
|
|
|
return Promise.reject({ status: res.status, text: res.statusText });
|
|
}
|
|
}
|
|
|
|
export function fetchGet(url, params = {}) {
|
|
return fetch(formatUrl(url, params), {
|
|
method: "GET",
|
|
credentials: "include",
|
|
}).then(authCheck);
|
|
}
|
|
|
|
export function fetchPost(url, data) {
|
|
return fetch(formatUrl(url), {
|
|
method: "POST",
|
|
credentials: "include",
|
|
headers: {
|
|
"Content-Type": "application/json; charset=utf-8",
|
|
},
|
|
body: JSON.stringify(data),
|
|
}).then(authCheck);
|
|
}
|