Skip to content

Commit

Permalink
Add constants for helping in configuration of body parser
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelBCarter committed Mar 13, 2024
1 parent b4b3523 commit df04cb8
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/middleware/jsonBodyParser/jsonBodyParser.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import bodyParser, { OptionsJson } from 'body-parser'
import { NextHandleFunction } from 'connect'
import { NextFunction, Request, Response } from 'express'

const bodyParserInstance = bodyParser.json({ type: ['application/json', 'text/json'] })
/**
* The default maximum request body size for the JSON Body Parser
*/
export const DefaultJsonBodyParserOptionsLimit = '100kb'

// If we do not trap this error, then it dumps too much to log, usually happens if request aborted
export const jsonBodyParser = (req: Request, res: Response, next: NextFunction) => {
try {
bodyParserInstance(req, res, next)
} catch (ex) {
const error = ex as Error
console.log(`bodyParser failed [${error.name}]: ${error.message}`)
}
}
/**
* The default MIME types for the JSON Body Parser
*/
export const DefaultJsonBodyParserOptionsTypes = ['application/json', 'text/json']

export const DefaultJsonBodyParserOptions: OptionsJson = { type: ['application/json', 'text/json'] }
/**
* The default options for the JSON Body Parser
*/
export const DefaultJsonBodyParserOptions: OptionsJson = {
limit: DefaultJsonBodyParserOptionsLimit,
type: DefaultJsonBodyParserOptionsTypes,
}

/**
* Get a JSON Body Parser connect middleware handler
Expand All @@ -36,3 +39,8 @@ export const getJsonBodyParser = (options: OptionsJson = DefaultJsonBodyParserOp
}
return ret
}

/**
* A JSON Body Parser middleware handler initialized with the default options
*/
export const jsonBodyParser = getJsonBodyParser()

0 comments on commit df04cb8

Please sign in to comment.