« index

Coverage for /Users/yunong/workspace/node-restify/lib/plugins/json_body_parser.js : 94%

72 lines | 68 run | 4 missing | 0 partial | 13 blocks | 11 blocks run | 2 blocks missing

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

  // Copyright 2012 Mark Cavage, Inc.  All rights reserved.
  
  var assert = require('assert-plus');
  
  var bodyReader = require('./body_reader');
  var errors = require('../errors');
  
  
  ///--- API
  
  /**
   * Returns a plugin that will parse the HTTP request body IFF the
   * contentType is application/json.
   *
   * If req.params already contains a given key, that key is skipped and an
   * error is logged.
   *
   * @return {Function} restify handler.
   * @throws {TypeError} on bad input
   */
  function jsonBodyParser(options) {
      assert.optionalObject(options, 'options');
      options = options || {};
  
      var override = options.overrideParams;
  
      function parseJson(req, res, next) {
          if (req.getContentType() !== 'application/json' || !req.body) {
              next();
              return;
          }
  
          var params;
          try {
              params = JSON.parse(req.body);
          } catch (e) {
              next(new errors.InvalidContentError('Invalid JSON: ' +
                  e.message));
              return;
          }
  
          if (options.mapParams !== false) {
              if (Array.isArray(params)) {
                  req.params = params;
              } else if (typeof (params) === 'object' && params !== null) {
                  Object.keys(params).forEach(function (k) {
                      var p = req.params[k];
                      if (p && !override)
                          return (false);
                      req.params[k] = params[k];
                      return (true);
                  });
              } else {
                  req.params = params || req.params;
              }
          } else {
              req._body = req.body;
          }
  
          req.body = params;
  
          next();
      }
  
      var chain = [];
      if (!options.bodyReader)
          chain.push(bodyReader(options));
      chain.push(parseJson);
      return (chain);
  }
  
  module.exports = jsonBodyParser;
« index | cover.io