Skip to content

Commit 584cfcf

Browse files
fix(server): restore original request.emit method in Node Body Limit Plugin (#863)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * More accurate enforcement of maximum request body size, leveraging Content-Length when available. * Consistent 413 Payload Too Large errors without duplicate or premature checks. * Prevents over-reading by tracking streamed body size per chunk. * **Refactor** * Improved stability of request event handling during and after middleware execution, ensuring original behavior is restored. * Streamlined internal flow to perform size checks once and maintain reliable processing of incoming requests. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent f9e0a4c commit 584cfcf

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

packages/server/src/adapters/node/body-limit-plugin.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Context } from '../../context'
22
import type { NodeHttpHandlerOptions } from './handler'
33
import type { NodeHttpHandlerPlugin } from './plugin'
44
import { ORPCError } from '@orpc/client'
5+
import { once } from '@orpc/shared'
56

67
export interface BodyLimitPluginOptions {
78
/**
@@ -26,17 +27,13 @@ export class BodyLimitPlugin<T extends Context> implements NodeHttpHandlerPlugin
2627
options.adapterInterceptors ??= []
2728

2829
options.adapterInterceptors.push(async (options) => {
29-
let isHeaderChecked = false
30-
31-
const checkHeader = () => {
32-
if (!isHeaderChecked && Number(options.request.headers['content-length']) > this.maxBodySize) {
30+
const checkHeader = once(() => {
31+
if (Number(options.request.headers['content-length']) > this.maxBodySize) {
3332
throw new ORPCError('PAYLOAD_TOO_LARGE')
3433
}
34+
})
3535

36-
isHeaderChecked = true
37-
}
38-
39-
const originalEmit = options.request.emit.bind(options.request)
36+
const originalEmit = options.request.emit
4037

4138
let currentBodySize = 0
4239

@@ -51,10 +48,15 @@ export class BodyLimitPlugin<T extends Context> implements NodeHttpHandlerPlugin
5148
}
5249
}
5350

54-
return originalEmit(event, ...args)
51+
return originalEmit.call(options.request, event, ...args)
5552
}
5653

57-
return options.next()
54+
try {
55+
return await options.next(options)
56+
}
57+
finally {
58+
options.request.emit = originalEmit
59+
}
5860
})
5961
}
6062
}

0 commit comments

Comments
 (0)