Skip to content

Commit

Permalink
perf: use the node require cache instead of custom caching
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip9587 committed Nov 19, 2024
1 parent 80fbb76 commit 686593e
Showing 1 changed file with 4 additions and 54 deletions.
58 changes: 4 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,6 @@

'use strict'

/**
* Cache of loaded parsers.
* @private
*/

var parsers = Object.create(null)

/**
* @typedef Parsers
* @type {function}
Expand All @@ -37,7 +30,7 @@ exports = module.exports = bodyParser
Object.defineProperty(exports, 'json', {
configurable: true,
enumerable: true,
get: createParserGetter('json')
get: () => require('./lib/types/json')
})

/**
Expand All @@ -48,7 +41,7 @@ Object.defineProperty(exports, 'json', {
Object.defineProperty(exports, 'raw', {
configurable: true,
enumerable: true,
get: createParserGetter('raw')
get: () => require('./lib/types/raw')
})

/**
Expand All @@ -59,7 +52,7 @@ Object.defineProperty(exports, 'raw', {
Object.defineProperty(exports, 'text', {
configurable: true,
enumerable: true,
get: createParserGetter('text')
get: () => require('./lib/types/text')
})

/**
Expand All @@ -70,7 +63,7 @@ Object.defineProperty(exports, 'text', {
Object.defineProperty(exports, 'urlencoded', {
configurable: true,
enumerable: true,
get: createParserGetter('urlencoded')
get: () => require('./lib/types/urlencoded')
})

/**
Expand All @@ -85,46 +78,3 @@ Object.defineProperty(exports, 'urlencoded', {
function bodyParser () {
throw new Error('The bodyParser() generic has been split into individual middleware to use instead.')
}

/**
* Create a getter for loading a parser.
* @private
*/

function createParserGetter (name) {
return function get () {
return loadParser(name)
}
}

/**
* Load a parser module.
* @private
*/

function loadParser (parserName) {
var parser = parsers[parserName]

if (parser !== undefined) {
return parser
}

// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}

// store to prevent invoking require()
return (parsers[parserName] = parser)
}

0 comments on commit 686593e

Please sign in to comment.