Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: use the node require cache instead of custom caching #562

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}