我有几个ES6模块的导出函数,如:
export const funA = params => 'hello funA';
export const funB = params => 'hello funB';
我想在导出之前将它们包装起来:
const wrapper = params => fun => {
// some extra logic
Object.assign(params, { extra: 'data' });
return fun(params);
};
export const funA = wrapper(params => 'hello funA');
export const funB = wrapper(params => 'hello funB');
它以这种方式工作,但我想知道是否有可能在没有funA
调用的情况下定义funB
和wrapper
,其方式类似于:
import { mapValues } from 'lodash';
const wrapper = params => fun => {
// some extra logic
Object.assign(params, { extra: 'data' });
return fun(params);
};
const funA = params => 'hello funA';
const funB = params => 'hello funB';
export default mapValues({ funA, funB }, wrapper);
上面代码段的问题是不使用命名导出。
我可以实现命名导出,并可以动态地用wrapper
中间件包装它们吗?
你要在哪里确定哪个包装中间件?
你可以做点什么
export const funA = middleware => params => 'funA'
export const funB = middleware => params => 'funB'
然后在呼叫现场:
import { funA } from './module.js'
const funFunA = middleware(funA)
但这听起来越来越像一个功能组合的案例:
import { funA } from './module.js'
import { nextFun } from './other.js'
const funFunA = compose(nextFun, funA)
根据您的需要,使用像Arrow
monad这样的东西也值得您
https://evilsoft.github.io/crocks/docs/crocks/Arrow.html
编辑:
const _funA = a => b
export const funA = (...args) => {
switch (currentMood) {
case 'saucy': return sauce(_funA(...args))
default: return _funA(...args)
}
如果你想避免在每一行重复wrapper
,你可以使用解构赋值和命名导出。但是,这需要重复{ funA, funB, ..., funXYZ }
。
import { mapValues } from 'lodash';
const wrapper = params => fun => {
// some extra logic
Object.assign(params, { extra: 'data' });
return fun(params);
};
let funA = params => 'hello funA';
let funB = params => 'hello funB';
let { funA, funB } = mapValues({ funA, funB }, wrapper);
export { funA, funB };