Rowan
A lightweight async middleware library.
Usage
Rowan can be used to build asynchronous middleware-style control-flow and error-handling, with particular focus on providing a rich typescript experience.
Create an instance of the Rowan class (or derivation) and call use
with a middleware function
; // Create a (derived) app; // Add middleware and handlersapp.use;
Once the middleware is all setup you call process
and pass along the context.
// Use it await app.execute;
... which in this example would output to console:
foo: bar!
Processors
Processors are either a Handler<Ctx>
, AutoHandler<Ctx>
or Middleware<Ctx>
type signature.
- Handler is a two-parameter function that will be given the
ctx
andnext
callback and should return a Promise. You are required to callnext
if you wish processing to continue to the next middleware processors in the chain.
app.use;
- AutoHandler is a one-parameter function that will be given the
ctx
object. The next processor in the chain will automatically be called for you, unless you throw an Error.
app.use;
- Middleware is a object containing a method
process
that will be called with two-parameters:ctx
andnext
. It is expected thatprocess
will return aPromise<void>
.
app.use;
Helpers
after-if
calls next and if the predicate returns true executes its middleware
; foo.usenew AfterIf ctx.valid, ; foo.use main.catchconsole.log;
outputs:
validate...
validate...
valid message: hello world
after
calls next first, then executes its own middleware afterwards
; foo.usenew After; foo.use; main.catchconsole.log;
outputs:
processing...
hello
processing...
hello world
catch
wraps its own middleware with a try...catch
foo.use new Catch , new Rowan .use .use ; main.catchconsole.log;
outputs:
Moo!
caught: ctx must be 'foo'
if
; foo.use new If , , /** terminate if predicate() == true */ true, ; foo.use main.catchconsole.log;
outputs:
IF... foo
IF... foobar
Else... bar
Tools
Rowan.hierarchy()
used to build a meta hierarchy from processors that have a middleware
field defined.
;; bar.meta.name = "Bar"; bar.use, ; bar.useObject.assign, ; bar.use; foo.usebar; console.logJSON.stringifyRowan.hierarchyfoo, null, 2;
outputs:
Advanced
Rowan.process()
executes and chains a sequence of Middleware
, setting up the next
callback for each.
main.catchconsole.log;
outputs:
first
second
END
Rowan.convertToMiddleware()
used interally to convert supported Handler
types into valid Middleware
.
Rowan.convertToMiddleware, ;
results in:
{
meta: { name: 'foo' },
process: [Function]
}
Build
npm install
npm test
there is an example.ts
that you can run with ts-node
ts-node example
Credits
"Rowan" Icon courtesy of The Noun Project, by ludmil, under CC 3.0