Skip to content

Instantly share code, notes, and snippets.

@typoerr
Last active July 22, 2017 13:43
Show Gist options
  • Select an option

  • Save typoerr/d13c3af870a51f3be3416cdb4152195d to your computer and use it in GitHub Desktop.

Select an option

Save typoerr/d13c3af870a51f3be3416cdb4152195d to your computer and use it in GitHub Desktop.
import { MiddlewareAPI, Middleware, Dispatch } from 'redux';
import { async } from 'most-subject';
import { mergeArray, Stream } from 'most';
import enhance, { EnhancedStore } from './make-typed-dispatch';
export interface Action<T = any, K extends keyof T = any> {
type: K;
payload: T[K];
}
export interface MergedCtx<S, A> {
store: EnhancedStore<MiddlewareAPI<S>, A>;
}
export interface Epic<S, A, C = any> {
(action$: Stream<Action<A>>, context: C & MergedCtx<S, A>): Stream<any>;
}
export default function createEpicMiddleware<S, A, C>(epics: Epic<S, A, C>[], context: C) {
const middleware = (api: MiddlewareAPI<S>) => (next: Dispatch<S>) => {
const store = enhance(api);
const actionIn$ = async<any>();
const ctx = Object.assign(context, { store });
const epicArray$ = epics.map(ep => ep(actionIn$, ctx));
const epic$ = mergeArray(epicArray$);
epic$.drain();
return (action: any) => actionIn$.next(next(action));
};
return middleware as Middleware;
}
export function select<T, K extends keyof T>(type: K, action$: Stream<Action<T>>): Stream<T[K]> {
return (action$ as Stream<Action<T, K>>)
.filter(x => x.type === type)
.map(x => x.payload);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment