Skip to content

Instantly share code, notes, and snippets.

@ecmel
Last active November 7, 2017 10:44
Show Gist options
  • Save ecmel/7310c4f31f36dc1bfddf0e0a95220a3a to your computer and use it in GitHub Desktop.
Save ecmel/7310c4f31f36dc1bfddf0e0a95220a3a to your computer and use it in GitHub Desktop.
Mock adapter for axios
import Deferred from './Deferred'
function Maxios(axios) {
this.axios = axios
this.adapter = axios.defaults.adapter
}
Maxios.prototype.pending = {}
Maxios.prototype.init = function () {
const pending = this.pending
this.axios.defaults.adapter = function (config) {
const key = config.method + config.url
const watch = pending[key]
if (typeof watch !== 'undefined') {
return new Promise((resolve, reject) => {
const wd = watch.data
let data
if (typeof wd === 'function') data = wd(config)
else if (typeof wd.data === 'function') data = wd.data(config)
else if (typeof wd.data === 'undefined') data = wd
else data = wd.data
const status = wd.status || 200
const valid = config.validateStatus ? config.validateStatus(status) : true
const response = {
data,
status,
statusText: wd.statusText || (valid ? 'OK' : 'ERR'),
headers: wd.headers || {},
config
}
if (valid) resolve(response)
else reject(response)
setTimeout(() => {
delete pending[key]
watch.resolve(response)
}, 0)
})
}
return Promise.reject({ status: 500, config })
}
}
Maxios.prototype.done = function () {
this.axios.defaults.adapter = this.adapter
}
Maxios.prototype.request = function (method, url, response) {
const key = method + url
let watch = this.pending[key]
if (typeof watch !== 'undefined') {
throw 'maxios: There is a pending ' + method + ' request for ' + url
}
watch = new Deferred(response)
this.pending[key] = watch
return watch.promise
}
Maxios.prototype.get = function (url, response) {
return this.request('get', url, response)
}
Maxios.prototype.post = function (url, response) {
return this.request('post', url, response)
}
Maxios.prototype.delete = function (url, response) {
return this.request('delete', url, response)
}
Maxios.prototype.head = function (url, response) {
return this.request('head', url, response)
}
Maxios.prototype.put = function (url, response) {
return this.request('put', url, response)
}
Maxios.prototype.patch = function (url, response) {
return this.request('patch', url, response)
}
export default Maxios
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment