Created
September 26, 2017 04:21
-
-
Save mariocesar/e96f6cf6cb2db213173a9c08b9a9867a to your computer and use it in GitHub Desktop.
Axios single configured instance
This file contains 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
import axios from "axios"; | |
const singleton = Symbol(); | |
const singletonEnforcer = Symbol(); | |
function readCookie(name) { | |
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); | |
return (match ? decodeURIComponent(match[3]) : null); | |
} | |
class ApiService { | |
constructor(enforcer) { | |
if (enforcer !== singletonEnforcer) { | |
throw new Error('Cannot construct singleton'); | |
} | |
console.log(`API Service for ${location.protocol}//${location.host}/api`); | |
this.session = axios.create({ | |
baseURL: `${location.protocol}//${location.host}/api`, | |
headers: { | |
'X-Requested-With': 'XMLHttpRequest', | |
'X-CSRFToken': readCookie('csrftoken'), | |
}, | |
}); | |
} | |
static get instance() { | |
// Try to get an efficient singleton | |
if (!this[singleton]) { | |
this[singleton] = new ApiService(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
get = (...params) => this.session.get(...params); | |
post = (...params) => this.session.post(...params); | |
put = (...params) => this.session.put(...params); | |
patch = (...params) => this.session.patch(...params); | |
remove = (...params) => this.session.delete(...params); | |
} | |
export default ApiService.instance; |
How does this work, can some one explain, especially line 32
how to use this?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you also post this for typescript ?