Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using es6 class to extend Axios

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)
like image 736
ThomasReggi Avatar asked Mar 12 '23 07:03

ThomasReggi


2 Answers

axios currently does not currently export the Axios object it uses internally.

The .create() method only instantiates a new instance.

// Factory for creating new instances
axios.create = function create(defaultConfig) {
  return new Axios(defaultConfig);
};

I created a pr that exports the Axios class.

https://github.com/reggi/axios/commit/7548f2f79d20031cd89ea7c2c83f6b3a9c2b1da4

And a github issue here:

https://github.com/mzabriskie/axios/issues/320

like image 169
ThomasReggi Avatar answered Mar 18 '23 04:03

ThomasReggi


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.

like image 34
Tuvia Avatar answered Mar 18 '23 04:03

Tuvia