@ts-delight/pipe.macro
v1.0.0
Published
TypeScript friendly fluent pipeline API with support for async steps, additional arguments, early returns and reconciliation
Downloads
4
Maintainers
Readme
About
Babel macro to build pipeline of expressions for more readable left-to-right composition chains.
This plugin supports many niceties like support for awaiting on pipeline steps, support for railway oriented programming, side-effect steps etc. Go through the Features section below for detailed examples.
Example
Source:
import Pipe from '@ts-delight/pipe.macro';
const increment = i => i + 1;
const add = (i, j) => i + j;
const result = Pipe(20)
.thru(increment)
.thru(add, 2)();
// Transpiles to:
const increment = i => i + 1;
const add = (i, j) => i + j;
const result = add(increment(20), 2);
Note that the left-to-right composition chain was transpiled to right-to-left composition of plain javascript functions.
Also note that there is no runtime dependency. The import to Pipe macro was entirely compiled away.
Why ?
- Left-to-right (or top-to-bottom) logic flow is more readable.
- It is nice being able to compose much of logic through expressions (as opposed to a ton of intermediate variables).
This plugin may become obsolete once pipeline-proposal become supported by typescript (Relevant issue). If you don't care about type checking, then you can try out this babel-plugin.
Installation
This utility is implemented as a babel-macro.
Refer babel's setup instructions to learn how to setup your project to use babel for compilation.
- Install
babel-plugin-macros
and@ts-delight/pipe.macro
:
npm install --save-dev babel-plugin-macros @ts-delight/pipe.macro
- Add babel-plugin-macros to .babelrc (if not already preset):
// .babelrc
module.exports = {
presets: [
// ... other presets
],
plugins: [
'babel-plugin-macros', // <-- REQUIRED
// ... other plugins
],
};
Features
Multi-step chaining:
Multiple levels of invocation can be chained together
Pipe(value)
.thru(increment) // <- Executed 1st
.thru(
i => i - 1 // <- Executed 2nd
)(); // <- Get result
tap
for side-effects:
Pipe(value)
.thru(increment)
.tap(i => {
console.log(i);
}) // Intercept value without modifying result
.thru(increment)();
await
support:
We can await on results of one step before passing them to another
await Pipe(1) // The pipeline will result in a promise if await is used as a step
.thru(async i => i + 1)
.await()
.thru(j => j + 2)(); // Step after await receives a resolved value and not a promise
await invocations can only be used in contexts where ES7 await is allowed. So following is illegal (and will fail to compile):
const foo = () =>
Pipe(1)
.thru(async i => i + 1)
.await()(); // Await can not be used in a non-async function
Use object methods with tap and thru:
Pipe(new User({id: 1}))
.tap.register() // Delegate to method register of User for side effect
.await()
.thru.enroll() // Delegate to method enroll and continue chain with returned value
.await()
.thru.assignCourses()
Equivalent to:
(function() {
const user = new User({id: 1});
await user.register(); // Return value discarded (tap)
const enrollment = await user.enroll(); // Return value used for next step (thru)
return enrollment.assignCourses();
})()
This feature enables you to use third party classes in a fluent manner even if the original author didn't implement a fluent API.
There is atmost one immediately executed function expression generated per pipe, that too is only when side-effects / branching is involved.
Bailing early:
It is possible to have an early-return using bailIf
:
Pipe(1)
.thru(increment)
.bailIf(i => i === 2) // Predicate to determine if chain should exit early
.thru(increment) // Operations below are not executed
.thru(increment)(); // Result is 2
Reconcile bailed results:
We can unify bailed branches and restore pipeline processing through reconcile
:
Pipe(1)
.thru(increment)
.bailIf(i => i === 2)
.thru(increment) // Not executed
.reconcile() // Subsequent pipeline operations will get executed
.thru(increment)(); // Result is 3
Reconcile can take a function that receives the value (from primary chain or wherever we bailed) and returns a value to be used for subsequent processing
Pipe(1)
.thru(increment)
.bailIf(i => i === 2)
.thru(increment)
.reconcile(i => ` ${i} `)
.thru(i => i.trim())(); // Result is "2"
Usage with TypeScript
This library is type-safe and comes with type definitions.
All code must be processed through babel. Compilation through tsc (only) is not supported.
Recommended babel configuration:
// .babelrc
module.exports = {
presets: [
'@babel/preset-typescript',
// ... other presets
],
plugins: [
'babel-plugin-macros',
// ... other plugins
],
};
Caveats
Every Pipe chain must end with a final function invocation without interruptions.
For example:
const a = 10;
const intermediate = Pipe(a === 10);
const result = intermediate.thru(increment)();
Above code will fail to compile.
Because the entire Pipe chain is compiled away, anything return by Pipe, thru etc. can not be assigned, referenced, or used in any computation.
You may also like:
- if-expr.macro: Similar utility, providing a fluent expression-oriented macro replacement for if statement.
- switch-expr.macro: Similar utility, providing a fluent expression-oriented macro replacement for switch statement
License
MIT