refactor: replace axios with fetch (#41944)

This commit is contained in:
Oliver Eyton-Williams
2021-06-15 11:47:25 -07:00
committed by GitHub
parent a378bc6dd4
commit 82f3f6ae0c
9 changed files with 72 additions and 36 deletions
+26 -17
View File
@@ -1,41 +1,52 @@
import envData from '../../../config/env.json';
import axios from 'axios';
import Tokens from 'csrf';
import cookies from 'browser-cookies';
const { apiLocation } = envData;
const { apiLocation, environment } = envData;
const base = apiLocation;
const tokens = new Tokens();
axios.defaults.withCredentials = true;
// TODO: test on staging. Do we need 'include' everywhere?
const defaultOptions = {
credentials: environment === 'development' ? 'include' : 'same-site'
};
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
// via headers:
function setCSRFTokens() {
function getCSRFToken() {
const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
if (!_csrf) return;
axios.defaults.headers.post['CSRF-Token'] = tokens.create(_csrf);
axios.defaults.headers.put['CSRF-Token'] = tokens.create(_csrf);
if (!_csrf) {
return '';
} else {
return tokens.create(_csrf);
}
}
function get(path) {
return axios.get(`${base}${path}`);
return fetch(`${base}${path}`, defaultOptions).then(res => res.json());
}
export function post(path, body) {
setCSRFTokens();
return axios.post(`${base}${path}`, body);
return request('POST', path, body);
}
function put(path, body) {
setCSRFTokens();
return axios.put(`${base}${path}`, body);
return request('PUT', path, body);
}
// function del(path) {
// return axios.delete(`${base}${path}`);
// }
function request(method, path, body) {
const options = {
...defaultOptions,
method,
headers: {
'CSRF-Token': getCSRFToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
};
return fetch(`${base}${path}`, options).then(res => res.json());
}
/** GET **/
@@ -106,5 +117,3 @@ export function putUserUpdateEmail(email) {
export function putVerifyCert(certSlug) {
return put('/certificate/verify', { certSlug });
}
/** DELETE **/