Name: js-handler/node_modules/restify/lib/plugins/json_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: | |
| 7: | var bodyReader = require('./body_reader'); |
| 8: | var errors = require('../errors'); |
| 9: | |
| 10: | |
| 11: | |
| 12: | ///--- API |
| 13: | |
| 14: | /** |
| 15: | * Returns a plugin that will parse the HTTP request body IFF the |
| 16: | * contentType is application/json. |
| 17: | * |
| 18: | * If req.params already contains a given key, that key is skipped and an |
| 19: | * error is logged. |
| 20: | * |
| 21: | * @return {Function} restify handler. |
| 22: | * @throws {TypeError} on bad input |
| 23: | */ |
| 24: | function jsonBodyParser(options) { |
| 25: | assert.optionalObject(options, 'options'); |
| 26: | options = options || {}; |
| 27: | |
| 28: | var override = options.overrideParams; |
| 29: | |
| 30: | function parseJson(req, res, next) { |
| 31: | if (req.getContentType() !== 'application/json' || !req.body) { |
| 32: | next(); |
| 33: | return; |
| 34: | } |
| 35: | |
| 36: | var params; |
| 37: | try { |
| 38: | params = JSON.parse(req.body); |
| 39: | } catch (e) { |
| 40: | next(new errors.InvalidContentError('Invalid JSON: ' + |
| 41: | e.message)); |
| 42: | return; |
| 43: | } |
| 44: | |
| 45: | if (options.mapParams !== false) { |
| 46: | if (Array.isArray(params)) { |
| 47: | req.params = params; |
| 48: | } else if (typeof (params) === 'object') { |
| 49: | Object.keys(params).forEach(function (k) { |
| 50: | var p = req.params[k]; |
| 51: | if (p && !override) |
| 52: | return (false); |
| 53: | req.params[k] = params[k]; |
| 54: | return (true); |
| 55: | }); |
| 56: | } else { |
| 57: | req.params = params; |
| 58: | } |
| 59: | } else { |
| 60: | req._body = req.body; |
| 61: | } |
| 62: | |
| 63: | req.body = params; |
| 64: | |
| 65: | next(); |
| 66: | } |
| 67: | |
| 68: | var chain = []; |
| 69: | if (!options.bodyReader) |
| 70: | chain.push(bodyReader(options)); |
| 71: | chain.push(parseJson); |
| 72: | return (chain); |
| 73: | } |
| 74: | |
| 75: | module.exports = jsonBodyParser; |
