Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export enum PledgeStatus {
- Starting = "Pledge_Starting",
- Completed = "Pledge_Completed",
- Error = "Pledge_Error"
- }
- export type Pledge<T> =
- | { status: PledgeStatus.Starting }
- | { status: PledgeStatus.Completed; result: T }
- | { status: PledgeStatus.Error; error: Error };
- export type PledgeToPromise<AP> = {
- [P in keyof AP]: "pledge" extends P ? (AP[P] extends Pledge<infer R> ? Promise<R> : AP[P]) : AP[P];
- };
- interface WithPromise<R> {
- pledge: Promise<R>;
- }
- // tslint:disable-next-line:no-any
- function hasPledge<R>(obj: any): obj is WithPromise<R> {
- return "pledge" in obj && obj.pledge && obj.pledge instanceof Promise;
- }
- export function pledgeMiddleware<A>(dispatch: (a: A) => void): (action: PledgeToPromise<A>) => void {
- return action => {
- if (hasPledge(action)) {
- // tslint:disable-next-line:no-any
- const anyAction: any = action;
- dispatch({ ...anyAction, pledge: { status: PledgeStatus.Starting } });
- action.pledge
- .then(r => {
- dispatch({
- ...anyAction,
- pledge: { status: PledgeStatus.Completed, result: r }
- });
- })
- .catch((e: Error) => {
- dispatch({
- ...anyAction,
- pledge: { status: PledgeStatus.Error, error: e }
- });
- });
- } else {
- // tslint:disable-next-line:no-any
- return dispatch(action as any);
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement