Skip to content

Instantly share code, notes, and snippets.

@helderberto
Forked from mariocesar/api.js
Created January 20, 2020 14:15
Show Gist options
  • Save helderberto/9b103d12a1c0e649e1fa2c2e3c21a698 to your computer and use it in GitHub Desktop.
Save helderberto/9b103d12a1c0e649e1fa2c2e3c21a698 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment