Skip to content

Instantly share code, notes, and snippets.

@benosman
Last active April 29, 2020 18:58
Show Gist options
  • Save benosman/350196da44933bff26789ee64651e4af to your computer and use it in GitHub Desktop.
Save benosman/350196da44933bff26789ee64651e4af to your computer and use it in GitHub Desktop.
Vuex Store plugin to inject axios instance into actions for axios nuxt module: https://github.com/nuxt-community/modules/tree/master/modules/axios
import Vuex from 'vuex';
// Copied from vuex/src/utils
function isPromise (val) {
return val && typeof val.then === 'function'
}
// Based on registerAction from vuex/src/store.js
function patchAction (store, type, handler, local) {
const entry = store._actions[type] || (store._actions[type] = [])
// TODO: should we check if last item contains a wrappedActionHandler ?
if (entry.length > 0) entry.pop()
entry.push(function wrappedActionHandler (payload, cb) {
let res = handler({
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state,
$axios: store.$axios
}, payload, cb)
if (!isPromise(res)) {
res = Promise.resolve(res)
}
if (store._devtoolHook) {
return res.catch(err => {
store._devtoolHook.emit('vuex:error', err)
throw err
})
} else {
return res
}
})
}
// Based on installModule from vuex/src/store.js
function patchModule (store, path, module, hot) {
const namespace = store._modules.getNamespace(path)
const local = module.context
module.forEachAction((action, key) => {
const namespacedType = namespace + key
patchAction(store, namespacedType, action, local)
})
module.forEachChild((child, key) => {
patchModule(store, path.concat(key), child, hot)
})
}
export default function axiosStorePlugin() {
return store => {
// Patch all current modules to include $axios parameter in action handlers.
patchModule(store, [], store._modules.root)
// Patch registerModule to auto patch newly added dynamic modules
const orig = Vuex.Store.prototype.registerModule;
Vuex.Store.prototype.registerModule = function registerModule(path, rawModule) {
orig.call(this, path, rawModule);
patchModule(this, path, this._modules.get(path))
};
}
}
import axiosStorePlugin from '~/axios/store-plugin';
export const state = () => ({
})
export const actions = {
testAxios (ctx) {
let $axios = ctx.$axios
},
}
export const plugins = [
axiosStorePlugin()
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment