/ node_modules / body-parser / lib / utils.js
utils.js
 1  'use strict'
 2  
 3  /**
 4   * Module dependencies.
 5   */
 6  
 7  var bytes = require('bytes')
 8  var contentType = require('content-type')
 9  var typeis = require('type-is')
10  
11  /**
12   * Module exports.
13   */
14  
15  module.exports = {
16    getCharset,
17    normalizeOptions
18  }
19  
20  /**
21   * Get the charset of a request.
22   *
23   * @param {object} req
24   * @api private
25   */
26  
27  function getCharset (req) {
28    try {
29      return (contentType.parse(req).parameters.charset || '').toLowerCase()
30    } catch {
31      return undefined
32    }
33  }
34  
35  /**
36   * Get the simple type checker.
37   *
38   * @param {string | string[]} type
39   * @return {function}
40   */
41  
42  function typeChecker (type) {
43    return function checkType (req) {
44      return Boolean(typeis(req, type))
45    }
46  }
47  
48  /**
49   * Normalizes the common options for all parsers.
50   *
51   * @param {object} options options to normalize
52   * @param {string | string[] | function} defaultType default content type(s) or a function to determine it
53   * @returns {object}
54   */
55  function normalizeOptions (options, defaultType) {
56    if (!defaultType) {
57      // Parsers must define a default content type
58      throw new TypeError('defaultType must be provided')
59    }
60  
61    var inflate = options?.inflate !== false
62    var limit = typeof options?.limit !== 'number'
63      ? bytes.parse(options?.limit || '100kb')
64      : options?.limit
65    var type = options?.type || defaultType
66    var verify = options?.verify || false
67  
68    if (verify !== false && typeof verify !== 'function') {
69      throw new TypeError('option verify must be function')
70    }
71  
72    // create the appropriate type checking function
73    var shouldParse = typeof type !== 'function'
74      ? typeChecker(type)
75      : type
76  
77    return {
78      inflate,
79      limit,
80      verify,
81      shouldParse
82    }
83  }