Last active
November 7, 2017 10:44
-
-
Save ecmel/7310c4f31f36dc1bfddf0e0a95220a3a to your computer and use it in GitHub Desktop.
Mock adapter for axios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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