Name: js-handler/node_modules/restify/lib/plugins/form_body_parser.js
| 1: | // Copyright 2012 Mark Cavage, Inc. All rights reserved. |
| 2: | |
| 3: | var crypto = require('crypto'); |
| 4: | |
| 5: | var assert = require('assert-plus'); |
| 6: | var querystring = require('qs'); |
| 7: | |
| 8: | var bodyReader = require('./body_reader'); |
| 9: | var errors = require('../errors'); |
| 10: | |
| 11: | |
| 12: | |
| 13: | ///--- Globals |
| 14: | |
| 15: | var MIME_TYPE = 'application/x-www-form-urlencoded'; |
| 16: | |
| 17: | |
| 18: | |
| 19: | ///--- API |
| 20: | |
| 21: | /** |
| 22: | * Returns a plugin that will parse the HTTP request body IFF the |
| 23: | * contentType is application/x-www-form-urlencoded. |
| 24: | * |
| 25: | * If req.params already contains a given key, that key is skipped and an |
| 26: | * error is logged. |
| 27: | * |
| 28: | * @return {Function} restify handler. |
| 29: | * @throws {TypeError} on bad input |
| 30: | */ |
| 31: | function urlEncodedBodyParser(options) { |
| 32: | options = options || {}; |
| 33: | assert.object(options, 'options'); |
| 34: | |
| 35: | var override = options.overrideParams; |
| 36: | |
| 37: | function parseUrlEncodedBody(req, res, next) { |
| 38: | if (req.getContentType() !== MIME_TYPE || !req.body) { |
| 39: | next(); |
| 40: | return; |
| 41: | } |
| 42: | |
| 43: | try { |
| 44: | var params = querystring.parse(req.body); |
| 45: | if (options.mapParams !== false) { |
| 46: | var keys = Object.keys(params); |
| 47: | keys.forEach(function (k) { |
| 48: | var p = req.params[k]; |
| 49: | if (p && !override) |
| 50: | return (false); |
| 51: | |
| 52: | req.params[k] = params[k]; |
| 53: | return (true); |
| 54: | }); |
| 55: | } else { |
| 56: | req._body = req.body; |
| 57: | req.body = params; |
| 58: | } |
| 59: | } catch (e) { |
| 60: | next(new errors.InvalidContentError(e.message)); |
| 61: | return; |
| 62: | } |
| 63: | |
| 64: | req.log.trace('req.params now: %j', req.params); |
| 65: | next(); |
| 66: | } |
| 67: | |
| 68: | var chain = []; |
| 69: | if (!options.bodyReader) |
| 70: | chain.push(bodyReader(options)); |
| 71: | chain.push(parseUrlEncodedBody); |
| 72: | return (chain); |
| 73: | } |
| 74: | |
| 75: | module.exports = urlEncodedBodyParser; |
