mux icon indicating copy to clipboard operation
mux copied to clipboard

Extending the API (e.g. to support Immutable data structures)

Open ide opened this issue 8 years ago • 0 comments

We could make mux support non-standard data structures like the ones in Immutable.js by letting people write extensions. I prefer not to directly add support for Immutable.js to mux itself since everyone will want to add support for their own data structure library, so a way to write extensions seems best.

My current thinking is an API like this:

import { List, OrderedMap } from 'immutable';
import mux, { extendMux } from '@exponent/mux';

const muxWithImmutableSupport = extendMux(mux, async (mux, promises) => {
  // The `mux` function in the formal parameters is the copy of mux that you call from
  // your application. So if you've extended mux many times:
  //
  //   const muxWithImmutableAndBinaryTreeSupport = extendMux(
  //     extendMux(mux, handleImmutableObjects),
  //     handleBinaryTrees,
  //   );
  //
  // then `handleImmutableObject` should receive `muxWithImmutableAndBinaryTreeSupport`
  // so that if the Immutable objects contain binary trees they are recursively handled.

  // Should this run before or after mux has handled the standard JS data types?
  if (OrderedMap.isOrderedMap(promises)) {
    let keys = [...promises.keys()];
    let values = await Promise.all([...promises.values()].map(mux));
    return new OrderedMap(zip(keys, values));
  }

  // Do the same for other data types that your application uses...
  if (List.isList(promises)) {
    ...
  }

  // Don't worry about non-Immutable data types
  return promises;
});

ide avatar Jan 16 '17 21:01 ide