Skip to content

Commit 1fd3222

Browse files
authored
refactor: optimize raw and text parsers with shared passthrough function (#634)
1 parent 5d691ff commit 1fd3222

3 files changed

Lines changed: 17 additions & 14 deletions

File tree

lib/types/raw.js

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
var debug = require('debug')('body-parser:raw')
1414
var read = require('../read')
15-
var { normalizeOptions } = require('../utils')
15+
var { normalizeOptions, passthrough } = require('../utils')
1616

1717
/**
1818
* Module exports.
@@ -31,12 +31,8 @@ module.exports = raw
3131
function raw (options) {
3232
var normalizedOptions = normalizeOptions(options, 'application/octet-stream')
3333

34-
function parse (buf) {
35-
return buf
36-
}
37-
3834
return function rawParser (req, res, next) {
39-
read(req, res, next, parse, debug, {
35+
read(req, res, next, passthrough, debug, {
4036
...normalizedOptions,
4137

4238
// Skip charset validation and parse the body as is

lib/types/text.js

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
var debug = require('debug')('body-parser:text')
1414
var read = require('../read')
15-
var { normalizeOptions } = require('../utils')
15+
var { normalizeOptions, passthrough } = require('../utils')
1616

1717
/**
1818
* Module exports.
@@ -31,11 +31,7 @@ module.exports = text
3131
function text (options) {
3232
var normalizedOptions = normalizeOptions(options, 'text/plain')
3333

34-
function parse (buf) {
35-
return buf
36-
}
37-
3834
return function textParser (req, res, next) {
39-
read(req, res, next, parse, debug, normalizedOptions)
35+
read(req, res, next, passthrough, debug, normalizedOptions)
4036
}
4137
}

lib/utils.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ var typeis = require('type-is')
1111
/**
1212
* Module exports.
1313
*/
14-
1514
module.exports = {
1615
getCharset,
17-
normalizeOptions
16+
normalizeOptions,
17+
passthrough
1818
}
1919

2020
/**
@@ -83,3 +83,14 @@ function normalizeOptions (options, defaultType) {
8383
shouldParse
8484
}
8585
}
86+
87+
/**
88+
* Passthrough function that returns input unchanged.
89+
* Used by parsers that don't need to transform the data.
90+
*
91+
* @param {*} value
92+
* @return {*}
93+
*/
94+
function passthrough (value) {
95+
return value
96+
}

0 commit comments

Comments
 (0)