buildMiddleware => ts
This commit is contained in:
parent
ca89c53c0b
commit
beae30d091
@ -1,30 +0,0 @@
|
||||
import fp from 'lodash/fp';
|
||||
|
||||
const MiddlewareFor = (type,mw) => api => next => action => {
|
||||
if (type !== '*' && action.type !== type) return next(action);
|
||||
|
||||
return mw(api)(next)(action);
|
||||
};
|
||||
|
||||
export default function buildMiddleware(
|
||||
effects = {},
|
||||
actions = {},
|
||||
subduxes = {},
|
||||
) {
|
||||
return api => {
|
||||
for (let type in actions) {
|
||||
api.dispatch[type] = (...args) => api.dispatch(actions[type](...args));
|
||||
}
|
||||
|
||||
return original_next => {
|
||||
return [
|
||||
...fp.toPairs(effects).map(([type, effect]) =>
|
||||
MiddlewareFor(type,effect)
|
||||
),
|
||||
...fp.map('middleware', subduxes),
|
||||
]
|
||||
.filter(x => x)
|
||||
.reduceRight((next, mw) => mw(api)(next), original_next);
|
||||
};
|
||||
};
|
||||
}
|
42
src/buildMiddleware/index.ts
Normal file
42
src/buildMiddleware/index.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import fp from 'lodash/fp';
|
||||
|
||||
import { Middleware } from 'redux';
|
||||
import { Dictionary, ActionCreator, Action } from '../types';
|
||||
|
||||
const MiddlewareFor = (type: any, mw: Middleware ): Middleware => api => next => action => {
|
||||
if (type !== '*' && action.type !== type) return next(action);
|
||||
|
||||
return mw(api)(next)(action);
|
||||
};
|
||||
|
||||
type Next = (action: Action) => any;
|
||||
|
||||
function buildMiddleware(
|
||||
effects: Dictionary<Middleware>,
|
||||
actions: Dictionary<ActionCreator>,
|
||||
subMiddlewares: Middleware[],
|
||||
): Middleware
|
||||
function buildMiddleware(
|
||||
effects = {},
|
||||
actions = {},
|
||||
subduxes = {},
|
||||
) {
|
||||
return (api: any) => {
|
||||
for (let type in actions) {
|
||||
api.dispatch[type] = (...args:any[]) => api.dispatch(((actions as any)[type] as any)(...args));
|
||||
}
|
||||
|
||||
return (original_next: Next)=> {
|
||||
return [
|
||||
...fp.toPairs(effects).map(([type, effect]) =>
|
||||
MiddlewareFor(type,effect as Middleware)
|
||||
),
|
||||
...fp.map('middleware', subduxes),
|
||||
]
|
||||
.filter(x => x)
|
||||
.reduceRight((next, mw) => mw(api)(next), original_next);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default buildMiddleware;
|
@ -9,5 +9,7 @@ export type Dictionary<T> = { [key: string]: T };
|
||||
|
||||
export type Mutation<S> = (payload: any, action: Action) => (state: S) => S ;
|
||||
|
||||
export type ActionCreator = (...args: any[] ) => Action;
|
||||
|
||||
export type UpduxConfig = Partial<{
|
||||
}>;
|
||||
|
Loading…
Reference in New Issue
Block a user