Skip to content

Commit

Permalink
feat: add parsedMethods option to parse only the passed ones
Browse files Browse the repository at this point in the history
  • Loading branch information
3imed-jaberi committed Apr 16, 2023
1 parent 5a78111 commit 9f589fe
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ app.use((ctx) => {

- **enableRawChecking**: support the already parsed body on the raw request by override and prioritize the parsed value over the sended payload. (default is `false`)

- **parsedMethods**: declares the HTTP methods where bodies will be parsed, default `['POST', 'PUT', 'PATCH']`.

- **disableBodyParser**: you can dynamic disable body parser by set `ctx.disableBodyParser = true`.

```js
Expand Down
8 changes: 7 additions & 1 deletion src/body-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,13 @@ declare module 'http' {
*/
export function bodyParserWrapper(opts: BodyParserOptions = {}) {
const {
patchNode = false,
parsedMethods = ['POST', 'PUT', 'PATCH'],
detectJSON,
onError,
enableTypes = ['json', 'form'],
extendTypes = {} as NonNullable<BodyParserOptions['extendTypes']>,
enableRawChecking = false,
patchNode = false,
...restOpts
} = opts;
const isEnabledBodyAs = getIsEnabledBodyAs(enableTypes);
Expand Down Expand Up @@ -69,8 +70,13 @@ export function bodyParserWrapper(opts: BodyParserOptions = {}) {

return async function (ctx: Koa.Context, next: Koa.Next) {
if (
// method souldn't be parsed
!parsedMethods.includes(ctx.method.toUpperCase()) ||
// patchNode enabled and raw request already parsed
(patchNode && ctx.req.body !== undefined) ||
// koa request body already parsed
ctx.request.body !== undefined ||
// bodyparser disabled
ctx.disableBodyParser
)
return next();
Expand Down
10 changes: 9 additions & 1 deletion src/body-parser.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ import type * as Koa from 'koa';
export const supportedBodyTypes = ['json', 'form', 'text', 'xml'] as const;
export type BodyType = (typeof supportedBodyTypes)[number];

/**
* BodyParser Options
*/
export type BodyParserOptions = {
/**
* Patch request body to Node's 'ctx.req'
* declares the HTTP methods where bodies will be parsed.
* @default ['POST', 'PUT', 'PATCH']
*/
parsedMethods?: string[];
/**
* patch request body to Node's 'ctx.req'
* @default false
*/
patchNode?: boolean;
Expand Down

0 comments on commit 9f589fe

Please sign in to comment.