Skip to content

Commit

Permalink
Add JSON Body Parser helper
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelBCarter committed Mar 13, 2024
1 parent ad2e2de commit b4b3523
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/middleware/jsonBodyParser/jsonBodyParser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import bodyParser from 'body-parser'
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'] })
Expand All @@ -12,3 +13,26 @@ export const jsonBodyParser = (req: Request, res: Response, next: NextFunction)
console.log(`bodyParser failed [${error.name}]: ${error.message}`)
}
}

export const DefaultJsonBodyParserOptions: OptionsJson = { type: ['application/json', 'text/json'] }

/**
* Get a JSON Body Parser connect middleware handler
* @param options The options for the JSON Body Parser
* @returns A middleware function that parses JSON bodies
*/
export const getJsonBodyParser = (options: OptionsJson = DefaultJsonBodyParserOptions): NextHandleFunction => {
// Create closed instance of bodyParser to prevent instantiation of new instance on every request
const parser = bodyParser.json(options)

// If we do not trap this error, then it dumps too much to log, usually happens if request aborted
const ret: NextHandleFunction = (req, res, next) => {
try {
parser(req, res, next)
} catch (ex) {
const error = ex as Error
console.log(`bodyParser failed [${error.name}]: ${error.message}`)
}
}
return ret
}

0 comments on commit b4b3523

Please sign in to comment.