Created
August 11, 2017 15:56
-
-
Save hjzheng/3d8fa1e618c1e16ebcb8ed359fa3fd5f to your computer and use it in GitHub Desktop.
axios-resource
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 axios from 'axios'; | |
function mixParams(url, params) { | |
let copyParams = Object.assign({}, params); | |
let urls = url.replace(/\:([^/:?&]+)/g, ($0, $1) => { | |
delete copyParams[$1]; | |
return params[$1]; | |
}); | |
urls.includes('?') ? urls = urls + '&' : urls = urls + '?'; | |
for (let key in copyParams) { | |
urls += `${key}=${copyParams[key]}&`; | |
} | |
urls = urls.slice(0, -1); | |
return urls; | |
} | |
class Resource { | |
constructor(url, configActions = {}) { | |
this.url = url; | |
const res = new Resource(url); | |
const actions = Object.assign({}, Resource.defaultActions, configActions); | |
for (let action in actions) { | |
res[action] = function(params, data, config) { | |
actions[action].url = mixParams(actions[action].url || this.url, params); | |
if (['put', 'post', 'patch'].includes(actions[action].method.toLowerCase())) { | |
actions[action].data = data; | |
} else { | |
config = data; | |
} | |
return axios.request(Object.assign({}, actions[action], config)); | |
} | |
} | |
return res; | |
} | |
// get(params, config) { | |
// return axios.get(mixParams(this.url, params), config); | |
// } | |
// | |
// save(params, data, config) { | |
// return axios.post(mixParams(this.url, params), data, config); | |
// } | |
// | |
// query(params, config) { | |
// return axios.get(mixParams(this.url, params), config); | |
// } | |
// | |
// remove(params, config) { | |
// return axios.delete(mixParams(this.url, params), config); | |
// } | |
// | |
// delete(params, config) { | |
// return axios.delete(mixParams(this.url, params), config); | |
// } | |
// | |
// update(params, data, config) { | |
// return axios.put(mixParams(this.url, params), data, config) | |
// } | |
} | |
Resource.defaultActions = { | |
get: { | |
method: 'get' | |
}, | |
save: { | |
method: 'post' | |
}, | |
query: { | |
method: 'get' | |
}, | |
remove: { | |
method: 'delete' | |
}, | |
update: { | |
method: 'put' | |
} | |
}; | |
export default Resource; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment