Created
February 15, 2018 13:26
-
-
Save luxcem/35bee5894c89f880fb9173dd24cec3df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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