Skip to content

tiggerk/express-param

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

176 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

express-param

Express.js request parameters parsing middleware

Build Status NPM version

About

You can reduce amount of code. It can remove redundant code and generate high readability.

See below.

  • may be existing
function route(req, res, next) {
  var id = req.params.id
    , count = req.param('count') ? parseInt(req.param('count'), 10) : 10
    , order = req.param('order')
    , type = req.param('type')
    , name = req.param('name')
    , since = req.param('since')
    , from = req.param('from')
    , res_id = req.param('res_id');

  if (!res_id) return next(400);
  if (!name) return next(400);
  if (!order) order = 'desc';
  if (!type) type = 'integer';

  // some code...
}
  • after using this
function route(req, res, next) {
  var requiredParams = ['{id}', 'name', 'res_id']
    , optionalParams = ['int:id', 'float:avg', 'number:count|=10', 'order|=desc', 'type|=integer', 'since', 'from']
    , options;

  options = req.fetchParamter(requiredParams, optionalParams);

  if (req.checkParamErr(options)) return next(options);

	return res.send(options);
}

Parameter syntax

I was inspired by Spring Framework and Flask.

required parameter : Array

  • [element1, element2, element3, ...]
  • type:{parameter_name}
  • type:
    • type is optional(default string). number(int, float) or string. return variable with type.
    • {parameter_name}: {} is optional. but parameter name is required. if it include {}, it means that this is path variable
    ['number:{id}', 'string:username', 'address']

optional parameter : Array

  • [element1, element2, element3, ...]

  • type:parameter_name|=default_value

  • type:

    • type is optional(default string). number(int, float) or string. return variable with type.
    • parameter_name: required.
    • default_value: optional. if request object do not have specified parameter then assign this default value.
    ['int:count', 'order', 'string:option1|=Y']

parameter with multiple values

Selects the last parameter value for shield against HTTP pollution attacks.

GET /path?id=1&type=number&id=2&name=first&name=second

{id: 2, type: 'number', name: 'second'}

If you want to select multiple values from the parameter, use string type after separating the values with commas.

GET /path?id=1,2&type=number&name=first,second

{id: '1,2', type: 'number', name: 'first,second'}

Example

Here is a simple example.

var express = require('express');
var fetcher = require('express-param');
var app = express();
app.use(fetcher());

app.get('/path', function(req, res, next) {
  var requiredParams = ['id'];
  var optionalParams = ['count'];
  var options = req.fetchParamter(requiredParams, optionalParams);

  if (req.checkParamErr(options)) return next(options);

  return res.send(options);
});

Here is another example with express-param syntax

var fetcher = require('express-param');
var app = express();
app.use(fetcher());

app.get('/path/:id/', function(req, res, next) {
  var requiredParams = ['string:{id}'];
  var optionalParams = ['number:count|=10, order|=desc'];
  var options = req.fetchParamter(requiredParams, optionalParams);

  if (req.checkParamErr(options)) return next(options);

  console.log(options);
  {
    id: '10',
    count: 10,
    order: 'desc'
  }

  return res.send(options);
});

Another example

Custom request key name belong to req property of express

var express = require('express');
var fetcher = require('express-param');
var app = express();
app.use(fetcher({
  'ipaddr': 'ip'
}));

app.get('/path', function(req, res, next) {
  var requiredParams = ['id'];
  var optionalParams = ['count', 'ipaddr'];
  var options = req.fetchParamter(requiredParams, optionalParams);

  if (options.err) return next(options.err);

  /*
  options.ipaddr is equal to req.ip
  */
  return res.send(options.params);
});

API

  • fetchParameter(required[, optional])

    fetch parameters that are required and optional

Add ON

  • fetch geographic information

    It can fetch country information from remote ip address!

    var addOnOpt = {
      geoip: {
      	keyName: 'headers.x-forwarded-for'
      }
    };
    app.use(fetcher({
      'ipaddr': 'ip',
      'geo-info': 'headers.x-fetcher-geoinfo',
      'access-country': true
    }, addOnOpt));
    
    ////// ....
    
    console.log(req.headers['x-fetcher-geoinfo']);
    // or console.log(options['geo-info']);
    {
      range: [ 3479299040, 3479299071 ],
      country: 'US',
      region: 'CA',
      city: 'San Francisco',
      ll: [37.7484, -122.4156]
    }
    
    console.log(options['access-country']);
    'US'
  • fetch detail imsi information by mnc, mcc code

    It can generate detail imsi(country, operator...) information by mcc, mnc code!

var addOnOpt = {
  imsi: true
};
app.use(fetcher({
  'ipaddr': 'ip',
  'access-country': true
}, addOnOpt));

////// ....

// url maybe hostname/api?mnc=11&mcc=450.
// if only exist mcc then results array length may be greater than 1.

console.log(req.headers['x-fetcher-imsi'])
[{
  country_name: 'South Korea',
  country_code: 'KR',
  mcc: '450',
  mnc: '11',
  brand: 'SKTelecom',
  operator: 'Korea Cable Telecom(t-plus), Eco-mobile',
  status: 'Operational',
  bands: 'UMTS 2100'
}]

console.log(options['access-country']);
'KR'

Contributing

We'd love your contributions! Please send us Pull Requests. Also, read the contribution guidelines.

LICENSE

MIT


This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com

About

fetch express request parameters.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages

  • JavaScript 99.2%
  • Makefile 0.8%