I'm interesting in creating an API wrapper and extending from axios using es6 classes. How is this possible? Axios has a method .create() which allows you to generate a new axios object
class Api extends Axios {
constructor(...args){
super(..args)
this.defaults.baseURL = 'https://api.com'
}
cancelOrder (id) {
return this.put(`/cancel/order/${id}`)
}
}
I know I have access to this let instance = axios.create()
.
Any thoughts?
Attempt 1
import axios from 'axios'
const Axios = axios.create()
class Api extends Axios {
constructor (...args) {
super(...args)
this.defaults.baseURL = 'https://api.com'
}
cancelOrder (id) {
return this.put(`/cancel/order/${id}`)
}
}
let api = new Api()
api.cancelOrder('hi')
.then(console.log)
.catch(console.log)
Attempt 2
import axios from 'axios'
class Axios {
constructor () {
return axios.create()
}
}
class Api extends Axios {
constructor () {
super()
this.defaults.baseURL = 'https://api.com'
}
cancelOrder (id) {
return this.put(`/cancel/order/${id}`)
}
}
let api = new Api()
console.log(api.__proto__)
api.cancelOrder('hi')
.then(console.log)
.catch(console.log)
If you look at the source code of axios they do not seem to expose the "class" for Axios
, only an instance.
I do not believe that an instance object can be extended in es6.
Your second attempt seems most viable, but if you want to emulate every single axios
method, you may have a lot of overhead.