In this paper,
http
The client is
axios
Let’s start with a story
An API like AXIos that supports promises is already friendly, and once the request is successful we can retrieve the data returned by the back end from then’s Response. Such as:
axios.get('/user/12345')
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});Copy the code
The data is in Response. data, which means that we need to do one more processing for each request to get the actual data. Then, the back-end of the actual scene basically will not directly give us the data, it will do a layer of encapsulation, for example, the structure of Response. data will be like this:
{ "date": "2017-12-14 15:21:38", "success": true, "obj": { ... }}, "version" : "V1.0"Copy the code
So, response.data.obj is the data we really want, so we need to do one more processing for each request =_=
Suddenly one day, the back end says, “Response. data is no longer an object, it’s a JSON string, do something about it.” Parse (response.data).obj, half-life!
If the backend says, “I changed back to the object, you can undo the previous processing ~”… If the backend says, “Not all of them are objects, some of them are JSON strings, see the updated interface documentation…” If we had never met…
Later us
ES6 Proxy
Changing the default behavior of certain operations is equivalent to making changes at the language level and is therefore a form of metaprogramming (
meta programming
), that is, programming a programming language.
Proxy
A layer of “interception” is placed in front of the target object, through which all external access to the object must pass, thus providing a mechanism for filtering and overwriting external access.
To address this distress, we need to encapsulate all interface requests uniformly. This way, even if the back end changes all over the place, we only need to change one place or even not change!
const apiService = new Proxy(axios, {
get (target, propKey, receiver) {
return function (...args) {
return target[propKey](...args)
.then((res) => {
const resData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
return typeof resData.obj === 'string' ? JSON.parse(resData.obj) : resData.obj;
})
.catch((err) => {
throw err;
});
}
}
});Copy the code
The corresponding interface request section is changed to:
apiService.get('/user/12345')
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});Copy the code
“You change casually, I change calculate I lose!”