Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created September 26, 2017 04:21
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mariocesar/e96f6cf6cb2db213173a9c08b9a9867a to your computer and use it in GitHub Desktop.
Save mariocesar/e96f6cf6cb2db213173a9c08b9a9867a to your computer and use it in GitHub Desktop.
Axios single configured instance
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;
@ashinga48
Copy link

Cheers mate

@ayusch-apps-curefit
Copy link

Can you also post this for typescript ?

@SandeepVattapparambil
Copy link

How does this work, can some one explain, especially line 32

@rjasino
Copy link

rjasino commented Mar 9, 2022

how to use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment