Skip to content

Instantly share code, notes, and snippets.

@luxcem
Created February 15, 2018 13:26
Show Gist options
  • Save luxcem/35bee5894c89f880fb9173dd24cec3df to your computer and use it in GitHub Desktop.
Save luxcem/35bee5894c89f880fb9173dd24cec3df to your computer and use it in GitHub Desktop.
/*
* This file handle the calls to the api and manage validation (csrf token)
* */
import 'whatwg-fetch';
export default {
getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i += 1) {
const cookie = $.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === `${name}=`) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
getCsrf() {
if (!this.csrf) {
this.csrf = this.getCookie('csrftoken');
}
return this.csrf;
},
formData(data) {
const form_data = new FormData();
for (const key in data) {
form_data.append(key, data[key]);
}
return form_data;
},
ajax(method, url, data) {
const request = new Request(url, {
method,
redirect: 'follow',
credentials: 'include',
headers: {
'X-CSRFToken': this.getCsrf(),
},
body: data
});
return fetch(request);
},
get(url) {
return this.ajax('GET', url);
},
post(url, data) {
return this.ajax('POST', url, data);
},
put(url, data) {
return this.ajax('PUT', url, data);
},
delete(url, data) {
return this.ajax('DELETE', url, data);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment