Onion is a simple and flexible middleware stack that enables you to add a middleware layer to just about anything.
npm install onion
Stacking some skins is simple just get you a new onion
Onion = require 'onion'onion =onionstackconsolelog 'Hello'nextonionstackconsolelog name+'!'onionpeel 'World'
Now you could peel that onion
It is also possible to stack and peel just for specific events. Just give
stack a name and use
Onion = require 'onion'onion =onionstack 'foo'consolelog 'foo'onionstack 'bar'consolelog 'bar'onionpeelFor 'foo'onionpeelFor 'bar'
The innermost function is called if there are no skins left on the onion and
the last middleware calls
next(). This could be used to catch unwanted
behaviour or reply with an
404 status code when handling HTTP requests.
By default the innermost function does nothing.
Onion = require 'onion'onion =onionstackconsolelog 'just calling next'nextonionpeel
just calling next
If we replace the innermost function with something useful, we could get
= ->consolelog 'gives fancy text'onionpeel
just calling nextgives fancy text
The error skin is a special middleware that is executed if a middleware throws an error. The error middleware can then decide how to handle the error. The error is given to the middleware after the given arguments, that means that the error middleware has the same signature as any other middleware, but with an error object appended. For example
will print the error message to the console and call the next
middleware. By calling
next the error can be ignored, thus the next
middleware will be called.
Onion = require 'onion'onion =onionconstruct ->=consolelog 'skin 1'next=consolelog 'skin 2'nextreturn skin1skin2
The construct method takes a function that returns the middleware (the so called skin constructor). The given function is executed in the scope of the onion, to provide a flexible way for e.g. adding specific methods to the onion before a middleware gets stacked. For example
= ->@foobar = 'foobar'=if val is 'foobar'return 'it is foobar!'elsenextskin
will add the attribute
foobar to the onion and stack the middleware
skin that returns
'it is foobar!' if the given value was foobar.
onionconstruct skinconstructoronionfoobar # ~> 'foobar'onionpeel 'barfoo' # ~> undefinedonionpeel 'foobar' # ~> 'it is foobar!'
To summarize all possibilities to add a middleware:
funcfunc1func2event: 'foo'skin: funcevent: 'foo''bar'skin: funcevent: 'foo'skin: func1func2event: 'foo''bar'func1func2
and any multiples from above in an array, e.g.:
func1 event: 'foo''bar'skin: func2
func2 are middlewares.
Onion is distributed under the MIT license. See LICENCE file.