npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-logical-routes

v0.0.4

Published

A way of adding logic to your routes in a declarative way

Downloads

12

Readme

Build Status NPM version

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.put('/user/:id/edit', getUser, editUser )

app.post('/user/:id/items', getUser, addItem )

function editUser (req, res) {
	if (!(req.currentUser.isAdmin || req.currentUser.id == req.user.id))
		return next(Error('Unauthorized'))
	util.extend(req.user, req.body)
	req.user.save(function (err) {
		res.redirect('/user/'+req.user.id);
	})
}

function addItem (req, res) {
	if (!(req.currentUser.isAdmin || req.currentUser.id == req.user.id))
		return next(Error('Unauthorized'))
	UserItem(req.body).save(function (err, doc) {
		res.redirect('/user/'+req.user.id+'/item/'+doc._id);
	})
}

//And so on!

Notice we have duplicated this line

if (!(req.currentUser.isAdmin || req.currentUser.id == req.user.id))
	return next(Error('Unauthorized'))

Instead of copying and pasting that logic around we can put it into middleware functions

var isAdmin = function (req, res, next) { next(req.user.isAdmin) }
  , isSameUser = function (req, res, next) { next(req.user.id == req.target.id) }

Now lets wrap those logical tests into an or()

app.put('/user/:id/edit', getUser, or(isAdmin, isSameUser).then(editUser))

app.post('/user/:id/items', getUser, or(isAdmin, isSameUser).then(addItem))

//we took out the busness logic out of our domain logic

function editUser (req, res, next) {
	util.extend(req.user, req.body)
	req.user.save(function (err) {
		res.redirect('/user/'+req.user.id);
	})
}

function addItem (req, res, next) {
	UserItem(req.body).save(function (err, doc) {
		res.redirect('/user/'+req.user.id+'/item/'+doc._id);
	})
}

Or we could combine the isAdmin and isSameUser into a middleware

var isValidUser = or(isAdmin, isSameUser)

and then apply it

app.put('/user/:id/edit', getUser, isValidUser().succeed(editUser))

app.post('/user/:id/items', getUser, isValidUser().succeed(addItem))

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.put('/user/:id/edit', getUser, isValidUser().succeed(editUser).failure(goAway))

app.post('/user/:id/items', getUser, isValidUser().succeed(addItem).failure(goAway))

Say we want to combine all this logic into a single object

var getAndValidateUser = [getUser, or(isAdmin, isSameUser).failure(goAway)];

app.put('/user/:id/edit', getAndValidateUser , editUser)

app.post('/user/:id/items', getAndValidateUser, addItem)

API Documentation

fn(method)

This method will build us a function that will internally used the passed async method

e.g.

var every = fn('every')
	, validUser = every( isLoggedIn, isAllowed )

This object has the following chainable methods

succeed(fn)

When the operation succeeds, the passed method will be called

validUser.succeed(function (req, res, next) { /* do something */ next() })

failure(fn)

When the operation fails, the passed method will be called

validUser.failure(function (req, res, next) { /* do something with the errors */ next() })

The errors are stored on the request object

validUser.failure(function (req, res, next) {
	res.status(400).json(req.errors);
});

Say we have defined this middleware

var validUser = every( isLoggedIn, isAllowed )
	.failure(function (req, res, next) { res.redirect('/login') })

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.get('/resource/:id', validUser, getResource); 
app.get('/v1/resource/:id', validUser.failure(function (req, res, next) { 
	res.status(403).json(new Error('You must be logged in')) }), getResource);

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 = validUser();

Now we can modify the "failure" method

validUserClone.failure(function (req, res, next) {
	res.status(403).json(new Error('You must be logged in'))
})

We can easily take our previous example and do

app.get('/resource/:id', validUser, getResource); 
app.get('/v1/resource/:id', validUser().failure(function (req, res, next) { 
	res.status(403).json(new Error('You must be logged in')) }), getResource);

Better yet

app.get('/resource/:id', validUser, getResource); 
app.get('/v1/resource/:id', validUser().failure(die), getResource);

function die (req, res, next) {
	res.status(403).json(new Error('You must be logged in')) }
}

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
	.succeed(function (req, res, next) { 
		req.awesome = true
	})
	.then(function (req,res) { 
		res.json({awesome:req.awesome}) 
	})

and(...)

This method will produce an object with the same chainable functions as the result of fn('every')

var validUser = and (isLoggedIn, isAllowedToView)
	.failure(function (req, res) { 
		res.status(403).json(req.errors)
	})

app.get('/resource/:id', validUser, getResource);

or(...)

This method will produce an object with the same chainable functions as the result of fn('some')

var validUser = or (isAdmin, isAllowedToView )

app.get('/resource/:id', validUser, getResource);

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 = not(isLoggedIn);

app.get('/resource/:id', notLoggedIn.succeed(showLogin), validUser, getResource);