Giter Site home page Giter Site logo

fusion-rpc-redux's Introduction

fusion-rpc-redux

Build status

A collection of helper functions for working with Redux and RPC together

If using RPC from React components, you should use fusion-plugin-rpc-redux-react instead of this package.


Table of contents


Installation

yarn add fusion-rpc-redux

API

createRPCActions

import {createRPCActions} from 'fusion-rpc-redux';

Creates start, success and failure actions for an RPC method name. Basically, assuming a RPC method named myMethod, it lets you write start({foo: 123}) instead of {type: 'MY_METHOD_START', payload: {foo: 123}}

Types
const actions: Actions = createRPCActions((rpcId: string));
  • rpcId: string - The RPC method name
  • returns actions: {start: (arg:T) => Action<T>, success: (arg:T) => Action<T>, failure: (T) => Action<T>}
type Action<T> = {
  type: string,
  payload: T,
};

For example, if rpcId is doSomething, createRPCActions generates the actions DO_SOMETHING_START, DO_SOMETHING_SUCCESS, and DO_SOMETHING_FAILURE.

createRPCReducer

import {createRPCReducer} from 'fusion-rpc-redux';

Creates a reducer that is composed of reducers that respond to start, success and failure actions.

const reducer: Reducer = createRPCReducer(rpcId: string, {
  start: ?Reducer,
  success: ?Reducer,
  failure: ?Reducer,
}, defaultValue: any);

fusion-rpc-redux's People

Contributors

albertywu avatar alexmsmithca avatar cdlewis avatar chrisdothtml avatar ganemone avatar hugoe29 avatar ian505c5 avatar kevingrandon avatar ksheedlo avatar lhorie avatar nadiia avatar renovate-bot avatar renovate[bot] avatar rtsao avatar sblotner avatar uberopensourcebot avatar vjocw avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

fusion-rpc-redux's Issues

Update reactors interface

  • rename createRPCReactor to createRPCReactors
  • update createRPCReactors to return reactors directly

Pluck properties off error object when dispatching failure action

Error objects do not serialize nicely by default. For example:

Object.keys(JSON.parse(JSON.stringify(new Error('Some message')))).length // 0
Object.keys({...new Error('Some message')}).length // 0

In order to fix this, we should pluck the message, code, and meta properties off the error object for the error action payload.

[feature request] pass `args` to both success + failure reducer handlers

Type of issue

Feature Request

Description

If you have a reducer that stores normalized data for a collection keyed by ID, you need to be able to set individual loading, error, and success states for each individual item.

Current behavior

Right now for the error case, there is no way to do this.

contrived example, consider an app that represents a bookshelf of books you are currently reading. Imagine your backend has 2 api endpoints:

/api/me/books

{
    books: Array<{|id: string, name: string, coverImageUrl: string|}>
}

/api/books/:bookId

{
    name: string,
    coverImageUrl: string,
    markdownBookSummary: string,
    reviews: Array<{|reviewerName: string, markdownReview: string|}>
}

and the following reducers

function getInitialState() {
  return {
    booksById: {
      [string]: Book
    }
  };
}

start(
    state?,
    action: {payload: {bookId: string}}
  ) {
    return setBook(
      state,
      bookId,
      {
        isLoading: true,
      }
    );
  },
  success(
    state?,
    action: {payload: book}
  ) {
    return setBook(
      state || getInitialState(),
      // workaround by using book.id ?,
      {
        isLoading: false,
        data: action.payload,
      }
    );
  },
  failure(state?, action: {payload: *}) {
    return setBook(
      state || getInitialState(),
      // OH NO, I DON'T KNOW WHICH BOOK FAILED TO LOAD!!!
      {
        isLoading: false,
        error: action.payload,
      }
    );
  },

One workaround for the success case, is to update the backend to attach the id to the entity response, but for the error case, there is no way to guarantee you can pass back the original id passed to the server in the error response.

Expected behavior

Not sure, maybe add an option to transform(args, resp) defaulting to (args, resp) => resp before dispatching when creating the reducer in createRPCReducer ?

It's easy to just append the args to payload but then you worry about namespacing.

Allow mapStateToProps to amend existing arguments

In createRPCHandler, mapStateToProps can currently only overwrite method arguments, rather than amend. It would be helpful in the future to allow for consumers to be able to map default values from their redux store in say a handler factory.

The following change to pass args should resolve this.

if (mapStateToParams) { args = mapStateToParams(store.getState(), args); }

Flow type checking does not accept string literals for RPC id

Type of issue

bug

Description

flow type checking fails when I use a string literal as the RPC name. I want it to succeed.

Current behavior

Flow type checking fails when I use a string literal as the RPC name

┌─[ken][ksheedlo-C02RC1GZG8WM][±][add-get-template-rpc U:5 ?:1 ✗][~/unpm-code/web-search-emoji]
└─▪ yam flow
yarn run v1.3.2
$ flow check
Error: src/reducers/template.js:41
 41: const getTemplateRPCReducer = createRPCReducer('getTemplate', {
                                                    ^^^^^^^^^^^^^ string. This type is incompatible with the expected param type of
 43:   rpcId: String,
              ^^^^^^ String. See: node_modules/fusion-rpc-redux/src/index.js:43


Found 1 error
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Expected behavior

┌─[ken][ksheedlo-C02RC1GZG8WM][±][add-get-template-rpc U:6 ?:1 ✗][~/unpm-code/web-search-emoji]
└─▪ yam flow
yarn run v1.3.2
$ flow check
Found 0 errors
✨  Done in 4.70s.

Steps to reproduce

  1. Import createRPCReducer
  2. Call it in a flow file as createRPCReducer('stringLiteral', { ... })
  3. Run a flow typecheck

Your environment

  • fusion-rpc-redux version: 1.0.1

  • Node.js version (node --version): v8.9.4

  • npm version (npm --version): 5.6.0 (I'm using Yarn)

  • Operating System: macOS 10.13.3

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Preset name not found within published preset config (monorepo:angularmaterial). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Wrapping createRPCReducer with another function will make error swallowed

Type of issue

Bug

Description

function withAuthCheck(originalHandler) {
  return (state, action) => {
    const {noExistLa} = action;
    // TODO no error, wtf?
    if (noExistLa.whatever) {
      return {};
    }
    return originalHandler(state, action);
  };
}

export default reduceReducers(
  (state) => state || someDefaultState,
  createRPCReducer(rpcIds.rpcGetDashboards, {
    start: ...,
    success: withAuthCheck((state, action) => {
      return {
        ...state,
      };
    }),
    failure: ...,
  }),
);

There's no error saying that can't get 'whatever' from undefined or anything at all.
Everything just runs like normally.

Current behavior

No error. Everything just runs.

Expected behavior

An error should have been thrown.

Steps to reproduce

Provided code example above.

Your environment

  • fusion-rpc-redux version: ^1.0.2

  • Node.js version (node --version): 8.11.1

  • npm version (npm --version): 5.6.0

  • Operating System: MacOS 10.13.4

Improve flow types with reactors

Type of issue

Feature request

Description

There currently isn't great support for flow types with reactors. The createRPCReactors api does not enforce that the flow types of all the reactors match, so users are required to manually type these apis.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.