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-route-params

v1.0.1

Published

Express route param validation with regexp or function

Downloads

1

Readme

express-route-params

Use app.param / router.param to apply matching and validation rules to a route parameter in express. Parameters can be validated through regular expression or function.

Usage

$ npm install --save express-route-params

The package is automatically applied as soon as you require it into you project. You must required it before any app or router instance is created:


// require the package before the app is created
var params = require('express-route-params'),
    app = require('express')();

or even:

var app = require('express-route-params').express();

now you can apply validation to your route params:

app.param('name', /^[a-z]+$/i)
   .param(['id', 'age'], parseInt)

// matches only if the `id` can be parsed to integer
   .get('/user/:id', function(req, res, next){})

// matches only if `name` contains only letters
   .get('/user/:name', function(req, res, next){ })

The package internaly requires express and gracefully modifies the .param method. In some edge cases you may need to apply it manually:

var express = require('express'),
	params = require('express-route-params');
	
// extend the `.param` method manually
params(express);

RegExp

The routes are matched only if the parameters satisfy the provided regexp. If capturing groups are used the value of the parameter in req.params will be replaced with the result of regexp.exec which may simplify the code in some cases:

app.param('range', /^(\d+)-(\d+)$/)

app.get('/:range', function(req, res, next){
	// this time `req.params.range` is already an array
	var range = req.params.range;
	
	res.send(`from ` + range[1] + ` to ` + range[2]);
})

NOTICE: never use the regular expression with the g flag since it will work as expected only once.

Function

You may use function to validate the parameters if it is with arity < 3 (less than 3 arguments), otherwise it will be considered as middleware and .param will fallback to its default behavior as described in the express documentation.

One common use case is to check if the provided parameter is valid mongoose id:

app.param('id', mongoose.Types.ObjectId.isValid);

The function should return one of the following for the parameter to be considered invalid:

var params = require('express-route-params');

params.invalids // --> [false, null, undefined, NaN]

The array may be modified or replaced for your needs, but you better keepfalse in there :). You may also replace the params.check function.

By default, the returned value from the validating function (if not true to avoid data loss) will be assigned in req.params to simulate the capturing groups effect in the regular expressions. A 3-rd parameter may be provided to alter/force this behavior:

// let `a` be the result of parseInt ('number')
app.param('a', parseInt);
	
// let `b` stay as it is ('string')
app.param('b', parseInt, false);

app.get('/:a/:b', function(req, res, next){
	typeof req.params.a // 'number'
	typeof req.params.b // 'string'
}	

One more example:

app.param('range', function(range){
	range = /^(\d+)-(\d+)$/.exec(range);
	return range && {from: range[1], to: range[2]}
})

app.get('/range', function(req, res, next){
	var range = req.params.range;
	res.send(`from ` + range.from + ' to ' + range.to);
})

apps and routers

You must know that params validation is defined independently for each express and express.Router instances and currently there is now effective way to have single global definition.


var router1 = express.Router(),
	router2 = express.Router();

router1.param('id', parseInt);
router2.param('id', parseInt);

Hey, if something is missing or you want to suggest improvements and features, you are wellcome.

License

MIT License

Copyright (c) 2017

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.