export function createRPCHandler()

in fusion-rpc-redux/src/index.js [126:178]


export function createRPCHandler({
  actions,
  store,
  rpc,
  rpcId,
  mapStateToParams,
  transformParams,
}: {
  actions?: RPCActionsType,
  store: Store<*, *, *>,
  rpc: any,
  rpcId: string,
  mapStateToParams?: (state: any, args?: any) => any,
  transformParams?: (params: any) => any,
}): RPCHandlerType {
  if (!actions) {
    actions = createRPCActions(rpcId);
  }
  return (args: any) => {
    if (mapStateToParams) {
      args = mapStateToParams(store.getState(), args);
    }
    if (transformParams) {
      args = transformParams(args);
    }
    store.dispatch(actions && actions.start(args));
    return rpc
      .request(rpcId, args)
      .then(result => {
        try {
          store.dispatch(actions && actions.success(result));
        } catch (e) {
          e.__shouldBubble = true;
          throw e;
        }
        return result;
      })
      .catch(e => {
        if (e.__shouldBubble) {
          delete e.__shouldBubble;
          throw e;
        }
        const error = Object.getOwnPropertyNames(e).reduce((obj, key) => {
          obj[key] = e[key];
          return obj;
        }, {});
        delete error.stack;
        error.initialArgs = args;
        store.dispatch(actions && actions.failure(error));
        return e;
      });
  };
}