vuex-local
Version:
Local state management within Vuex
70 lines (69 loc) • 3.12 kB
JavaScript
import { localKey, mapValues, mapKeys } from './utils';
export function registerLocalModule(store, modulePath, module) {
var state = module.state, _a = module.getters, getters = _a === void 0 ? {} : _a, _b = module.actions, actions = _b === void 0 ? {} : _b, _c = module.mutations, mutations = _c === void 0 ? {} : _c;
var name = modulePath[modulePath.length - 1];
store.registerModule(modulePath, {
state: state,
getters: mapLocalKeys(mapLocalGetters(getters, name), name),
actions: mapLocalKeys(mapLocalActions(actions, getters, name), name),
mutations: mapLocalKeys(mutations, name)
});
}
export function unregisterLocalModule(store, modulePath) {
store.unregisterModule(modulePath);
}
export function mapLocalKeys(obj, moduleName) {
return mapKeys(obj, function (_, key) { return localKey(key, moduleName); });
}
function mapLocalGetters(getters, moduleName) {
return mapValues(getters, function (getter) {
return function wrappedGetter(state, rootGetters, rootState) {
var localGetters = makeLocalGetters(Object.keys(getters), rootGetters, moduleName);
return getter(state, localGetters, rootState, rootGetters);
};
});
}
function mapLocalActions(actions, getters, moduleName) {
return mapValues(actions, function (action) {
return function wrappedAction(context, payload) {
// overwrite commit and dispatch to convert
// action and mutation type to prefixed format
var commit = context.commit, dispatch = context.dispatch;
context.commit = function localCommit(type, payload, options) {
if (options === void 0) { options = {}; }
if (typeof type === 'object') {
options = payload;
type = type.type;
payload = type;
}
return commit(options.root ? type : localKey(type, moduleName), payload, options);
};
context.dispatch = function localDispatch(type, payload, options) {
if (options === void 0) { options = {}; }
if (typeof type === 'object') {
options = payload;
type = type.type;
payload = type;
}
return dispatch(options.root ? type : localKey(type, moduleName), payload, options);
};
// expose real getters object as rootGetters
var rootGetters = context.getters;
context.rootGetters = rootGetters;
context.getters = makeLocalGetters(Object.keys(getters), rootGetters, moduleName);
// execute original action
action(context, payload);
};
});
}
function makeLocalGetters(getterKeys, getters, moduleName) {
var localGetters = {};
getterKeys.forEach(function (key) {
Object.defineProperty(localGetters, key, {
get: function () {
return getters[localKey(key, moduleName)];
}
});
});
return localGetters;
}