/*! Copyright (c) 2009-2014 TJ Holowaychuk <tj@vision-media.ca> */
/* > https://raw.githubusercontent.com/visionmedia/express/master/lib/middleware/query.js */

/**
 * Module dependencies.
 */

var qs = require('qs');
var parseUrl = require('parseurl');

/**
 * Query:
 *
 * Automatically parse the query-string when available,
 * populating the `req.query` object using
 * [qs](https://github.com/visionmedia/node-querystring).
 *
 * Examples:
 *
 *       .use(connect.query())
 *       .use(function(req, res){
 *         res.end(JSON.stringify(req.query));
 *       });
 *
 *  The `options` passed are provided to qs.parse function.
 *
 * @param {Object} options
 * @return {Function}
 * @api public
 */

module.exports = function query(options){
  return function query(req, res, next){
    if (!req.query) {
      req.query = ~req.url.indexOf('?')
        ? qs.parse(parseUrl(req).query, options)
        : {};
    }

    next();
  };
};
