« index

Coverage for /Users/yunong/workspace/node-restify/lib/plugins/fielded_text_body_parser.js : 89%

74 lines | 66 run | 8 missing | 5 partial | 6 blocks | 4 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

73

74

  /**
   * Dependencies
   */
  
  var csv = require('csv');
  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 if the
   * contentType is `text/csv` or `text/tsv`
   *
   * @return {Function} restify handler.
   * @throws {TypeError} on bad input
   */
  
  function fieldedTextParser(options) {
  
      assert.optionalObject(options, 'options');
      options = options || {};
  
      function parseFieldedText(req, res, next) {
  
          var contentType = req.getContentType();
  
          if (contentType !== 'text/csv' &&
              contentType !== 'text/tsv' &&
              contentType !== 'text/tab-separated-values' || !req.body) {
              next();
              return;
          }
  
  
          var hDelimiter = req.headers['x-content-delimiter'];
          var hEscape = req.headers['x-content-escape'];
          var hQuote = req.headers['x-content-quote'];
          var hColumns = req.headers['x-content-columns'];
  
  
          var delimiter = (contentType === 'text/tsv') ? '\t' : ',';
          delimiter = (hDelimiter) ? hDelimiter : delimiter;
          var escape = (hEscape) ? hEscape : '\\';
          var quote = (hQuote) ? hQuote : '"';
          var columns = (hColumns) ? hColumns : true;
  
          var parserOptions = {
              delimiter: delimiter,
              quote: quote,
              escape: escape,
              columns: columns
          };
  
          csv.parse(req.body, parserOptions, function (err, parsedBody) {
              if (err) {
                  return (next(err));
              }
              // Add an "index" property to every row
              parsedBody.forEach(function (row, index) {
                  row.index = index;
              });
              req.body = parsedBody;
              return (next());
          });
  
      }
  
      return (parseFieldedText);
  
  }
  
  module.exports = fieldedTextParser;
« index | cover.io