Express Logical Routes
A library for building middleware as a series of logic gates to reduce and reuse code.
Getting Started
> npm install
> npm test
Typical Middleware
Typically writing business rules in your routes may look like this.
app app { if !reqcurrentUserisAdmin || reqcurrentUserid == requserid return util requser} { if !reqcurrentUserisAdmin || reqcurrentUserid == requserid return } //And so on!
Notice we have duplicated this line
if !reqcurrentUserisAdmin || reqcurrentUserid == requserid return
Instead of copying and pasting that logic around we can put it into middleware functions
var { } { }
Now lets wrap those logical tests into an or()
app app //we took out the busness logic out of our domain logic { util requser} { }
Or we could combine the isAdmin and isSameUser into a middleware
var isValidUser =
and then apply it
app app
Here we used the "succeed()" method to editUser and addItem, we can also support a failure
NOTE that we called isValidUser() with no arguments. This creates a new middlware that we can attach succeed(), failure(), and then() methods to.
app app
Say we want to combine all this logic into a single object
var getAndValidateUser = getUser ; app app
API Documentation
fn(method)
This method will build us a function that will internally used the passed async method
e.g.
var every = validUser =
This object has the following chainable methods
succeed(fn)
When the operation succeeds, the passed method will be called
validUser
failure(fn)
When the operation fails, the passed method will be called
validUser
The errors are stored on the request object
validUser;
Say we have defined this middleware
var validUser =
And we want to reuse it but change how we handle the failure.
For instance we want to return a JSON response for our 'v1' api and
a redirect to the login page for the standard interface.
app; app;
By doing this we are actually replacing the failure function for validUser. If we want to reuse the logic but modify either "failure", "succeed", or "then" methods, we can call the middleware without parameters to clone it.
var validUserClone = ;
Now we can modify the "failure" method
validUserClone
We can easily take our previous example and do
app; app;
Better yet
app; app; { resstatus403 }}
All of theses capabilities are inherited to the other logic operators
then(fn)
After the succeed() or failure() method is called then the fn() passed will be called
validUser
and(...)
This method will produce an object with the same chainable functions as the result of fn('every')
var validUser = app;
or(...)
This method will produce an object with the same chainable functions as the result of fn('some')
var validUser = app;
not(...)
This method will produce an object with the same chainable functions as the result of fn('every') but only supports one middleware function
var notLoggedIn = ; app;