buildMiddleware => ts

This commit is contained in:
Yanick Champoux 2019-10-23 15:55:12 -04:00
parent ca89c53c0b
commit beae30d091
3 changed files with 44 additions and 30 deletions

View File

@ -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);
};
};
}

View 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;

View File

@ -9,5 +9,7 @@ export type Dictionary<T> = { [key: string]: T };
export type Mutation<S> = (payload: any, action: Action) => (state: S) => S ; export type Mutation<S> = (payload: any, action: Action) => (state: S) => S ;
export type ActionCreator = (...args: any[] ) => Action;
export type UpduxConfig = Partial<{ export type UpduxConfig = Partial<{
}>; }>;