All of our server API resources return as JSON object as follows:
{
data: {
... Business data from the controller
}
meta: {
... meta data added by middleware
}
}
The idea is that meta data is added to the json response which can be used to update vuex store data. Works great, and even though we are phasing it out to be replaced by pushe to more easily keep our client state current, we still have the wrapped data object returned from the server.
Basically, we have an axios interceptor which handles the meta part of the response, and then just throws the original data for processing by whatever vuejs component.
So that's the theory. This is how it works.
bootstrapping Axios
Axios is bootstrapped into the app as follows:
window.axios = require('axios');
Vue.prototype.$http = axios;
Notice we replaced Vue resource by axios in the past. Anyway. This is basically done before any of the other code.
The next part is adding the interceptor:
Bootstrapping interceptor
axios.interceptors.response.use(
(response) => {
window.app.$emit('update-meta-data', response.data.meta);
response.data = response.data.data;
return response;
},
(error) => {
... error handling goes here
}
);
A regular component
In any regular component, we can do the following:
this.$http.get();
The result, is that - for my component - the meta bit is correctly stripped by the interceptor. Works brilliantly.
... but with an mixin
I also have a mixin that I include in components; in these cases however, the interceptor does not work.
This is the mixin code:
module.exports = {
mounted: function() {
this.$http.get('/resource').then(
(response) => {
... here I expect to be able to do response.data
... but the response.data contains the original json object
... including both data and meta properties
}
)
}
}
The mixin is included in a component as follows:
<script>
module.exports = {
mixins:[require('../mixins/repository.js')],
...
}
</script>
when moving the mounted method from the mixin to the actual component, it works as expected. I don't understand why though.
I though that it was because this.$http may be another object without the interceptors, but that is not the case, because when I add console.log() devug prints in the interceptor, I see that for my calls from within the mixing, it does go through its logic. The only difference seems that response.data does not seem to be set to response.data.data of the original response.
I hope this all makes sense.
Thank you for your assistance!