action-chain
Why
All modern frameworks has some concept of an action. The purpose of an action is to perform side effects, this being changing the state of the application or talking to the server. How you express this action is different in the different frameworks and tools, but they typically have one thing in common... they are expressed as one function with imperative code.
There is nothing wrong with imperative code, we need it, but it has some limitations:
-
When a single function with imperative code grows it quickly becomes difficult to reason about what it does
-
There is no way to track what the function does, because it is low level and we typically point directly to other libraries and functions
-
It requires a lot of dicipline to make your code reusable and composable
action-chain moves you into a functional world by exposing a chaining API, much like RxJS. But instead of being focused on value transformation, action-chain is focused on side effects. With its "developer experience" driven implementation it allows for building developer tools that can visual all execution.
Create an action-chain
// The context holds all side effects you want to access in// your chain. Expressed as simple objects with methods. You would// use this to wrap existing libraries, exposing a domain specific// api for your action chain // You define your own factory for creating actions. It// can define an initial value type and returns an// action factory with the chain defined. You type out// conditional "Action" or "NoValueAction" to allow// typed actions to require a value and untyped actions// to not require a value
Define actions
.map` ` test'Bob' // "hello Bob"
Track actions
actionChain.on'action:start',actionChain.on'operator:start',actionChain.on'operator:end',actionChain.on'action:end',
Operators
do
Allows you to run effects and passes the current value a long to the next operator.
.do
map
Maps to a new value, passed to the next operator.
.mapvalue.toUpperCase
try
If returning a promise, run paths based on resolved or rejected.
.tryapi.getUser,
when
Executes true or false path based on boolean value.
.whenvalue.length > 3,
filter
Stops execution when false.
.filterfalse // does not run .map'foo'
debounce
Debounces execution.
.debounce100 // Runs when 100 milliseconds has passed since // last time the "test" action was called .map'foo'
Extend operators
// There are two types of actions. Actions that takes an initial value // And those who do not // You type out your operators and all of them will return either// an action with an initial value or not, based on the "InitialValue"// typing // Create a new actionFactory which composes the default one and implements// the new operators ? NoValueMyAction<Context, InitialValue, Value> : MyAction<Context, InitialValue, Value>