Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. export enum PledgeStatus {
  2. Starting = "Pledge_Starting",
  3. Completed = "Pledge_Completed",
  4. Error = "Pledge_Error"
  5. }
  6.  
  7. export type Pledge<T> =
  8. | { status: PledgeStatus.Starting }
  9. | { status: PledgeStatus.Completed; result: T }
  10. | { status: PledgeStatus.Error; error: Error };
  11.  
  12. export type PledgeToPromise<AP> = {
  13. [P in keyof AP]: "pledge" extends P ? (AP[P] extends Pledge<infer R> ? Promise<R> : AP[P]) : AP[P];
  14. };
  15.  
  16. interface WithPromise<R> {
  17. pledge: Promise<R>;
  18. }
  19. // tslint:disable-next-line:no-any
  20. function hasPledge<R>(obj: any): obj is WithPromise<R> {
  21. return "pledge" in obj && obj.pledge && obj.pledge instanceof Promise;
  22. }
  23.  
  24. export function pledgeMiddleware<A>(dispatch: (a: A) => void): (action: PledgeToPromise<A>) => void {
  25. return action => {
  26. if (hasPledge(action)) {
  27. // tslint:disable-next-line:no-any
  28. const anyAction: any = action;
  29. dispatch({ ...anyAction, pledge: { status: PledgeStatus.Starting } });
  30. action.pledge
  31. .then(r => {
  32. dispatch({
  33. ...anyAction,
  34. pledge: { status: PledgeStatus.Completed, result: r }
  35. });
  36. })
  37. .catch((e: Error) => {
  38. dispatch({
  39. ...anyAction,
  40. pledge: { status: PledgeStatus.Error, error: e }
  41. });
  42. });
  43. } else {
  44. // tslint:disable-next-line:no-any
  45. return dispatch(action as any);
  46. }
  47. };
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement