diff --git a/apps/content/docs/openapi/handler.mdx b/apps/content/docs/openapi/handler.mdx index 3576c2f84..70b040274 100644 --- a/apps/content/docs/openapi/handler.mdx +++ b/apps/content/docs/openapi/handler.mdx @@ -92,6 +92,23 @@ const handler = new OpenAPIHandler(router, { }) ``` +:::tip +Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error: + +```ts +;async ({ next, encodeError }) => { + const result = await next() + + if (!result.matched) { + return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) } + } + + return result +} +``` + +::: + ### Interceptors These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure. diff --git a/apps/content/docs/rpc/handler.mdx b/apps/content/docs/rpc/handler.mdx index 3bb8845dc..eac2322d8 100644 --- a/apps/content/docs/rpc/handler.mdx +++ b/apps/content/docs/rpc/handler.mdx @@ -162,6 +162,23 @@ const handler = new RPCHandler(router, { }) ``` +:::tip +Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error: + +```ts +;async ({ next, encodeError }) => { + const result = await next() + + if (!result.matched) { + return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) } + } + + return result +} +``` + +::: + ### Interceptors These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure. diff --git a/packages/node/src/tmp-file-upload-handler-plugin.test.ts b/packages/node/src/tmp-file-upload-handler-plugin.test.ts index c0cf97934..3d4e458b8 100644 --- a/packages/node/src/tmp-file-upload-handler-plugin.test.ts +++ b/packages/node/src/tmp-file-upload-handler-plugin.test.ts @@ -162,6 +162,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await interceptor({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -589,6 +590,7 @@ describe('tmpFileUploadHandlerPlugin', () => { const result = await interceptor({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1092,6 +1094,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await plugin.init({}).routingInterceptors![0]!({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1572,6 +1575,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await interceptor({ context: options.context, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1673,6 +1677,7 @@ describe('tmpFileUploadHandlerPlugin', () => { const interceptorOptions = { context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', diff --git a/packages/server/src/adapters/standard-peer/utils.test.ts b/packages/server/src/adapters/standard-peer/utils.test.ts index 3af1c485b..da4677bb8 100644 --- a/packages/server/src/adapters/standard-peer/utils.test.ts +++ b/packages/server/src/adapters/standard-peer/utils.test.ts @@ -39,8 +39,10 @@ describe('createStandardPeerRequestHandler', () => { }) it('returns 404 response when no procedure matched', async () => { + const notFound = { status: 404, headers: {}, body: 'encoded' } const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn(() => notFound), } as any const handleRequest = createStandardPeerRequestHandler(handler, { context: { context: true } }) @@ -53,13 +55,17 @@ describe('createStandardPeerRequestHandler', () => { signal: new AbortController().signal, }) - expect(result).toEqual({ status: 404, headers: {}, body: 'No procedure matched' }) + expect(result).toBe(notFound) + expect(handler.encodeError).toHaveBeenCalledWith( + expect.objectContaining({ code: 'NOT_FOUND', message: 'No procedure matched' }), + ) expect(handler.handle).toHaveBeenCalledTimes(1) }) it('context fallback to empty object when it undefined', async () => { const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn(), } as any const handleRequest = createStandardPeerRequestHandler(handler, {}) @@ -80,6 +86,7 @@ describe('createStandardPeerRequestHandler', () => { it('forwards a context function unresolved so the handler resolves it after its prefix check', async () => { const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn(), } as any const context = vi.fn(() => ({ db: 'postgres' })) diff --git a/packages/server/src/adapters/standard-peer/utils.ts b/packages/server/src/adapters/standard-peer/utils.ts index 238c1ba18..9d9225802 100644 --- a/packages/server/src/adapters/standard-peer/utils.ts +++ b/packages/server/src/adapters/standard-peer/utils.ts @@ -2,7 +2,10 @@ import type { StandardLazyRequest, StandardResponse } from '@standard-server/cor import type { Context } from '../../context' import type { FriendlyStandardHandlerHandleOptions, StandardHandler } from '../standard/index' -import { resolveFriendlyStandardHandlerHandleOptions } from '../standard/index' +import { + createNoProcedureMatchedError, + resolveFriendlyStandardHandlerHandleOptions, +} from '../standard/index' export function createStandardPeerRequestHandler( handler: StandardHandler, @@ -13,6 +16,6 @@ export function createStandardPeerRequestHandler( request, resolveFriendlyStandardHandlerHandleOptions(options), ) - return response ?? { status: 404, headers: {}, body: 'No procedure matched' } + return response ?? handler.encodeError(createNoProcedureMatchedError()) } } diff --git a/packages/server/src/adapters/standard/codec.ts b/packages/server/src/adapters/standard/codec.ts index 61bdd8b01..49724dad6 100644 --- a/packages/server/src/adapters/standard/codec.ts +++ b/packages/server/src/adapters/standard/codec.ts @@ -25,10 +25,5 @@ export interface StandardHandlerCodec { options: ResolvedStandardHandlerHandleOptions, ): Promisable - encodeError( - error: AnyORPCError, - procedure: AnyProcedure, - path: string[], - options: ResolvedStandardHandlerHandleOptions, - ): Promisable + encodeError(error: AnyORPCError): Promisable } diff --git a/packages/server/src/adapters/standard/handler.test.ts b/packages/server/src/adapters/standard/handler.test.ts index 12a70fc63..6b4e2dd43 100644 --- a/packages/server/src/adapters/standard/handler.test.ts +++ b/packages/server/src/adapters/standard/handler.test.ts @@ -116,6 +116,7 @@ describe('standardHandler', () => { expect(routingInterceptor).toHaveBeenCalledTimes(1) expect(routingInterceptor).toHaveBeenCalledWith({ next: expect.any(Function), + encodeError: expect.any(Function), request, context: OPTIONS.context, prefix: OPTIONS.prefix, @@ -433,12 +434,7 @@ describe('standardHandler', () => { matched: true, response: { status: 502, headers: {}, body: 'bad gateway' }, }) - expect(codec.encodeError).toHaveBeenCalledWith( - procedureError, - expect.anything(), - ['ping'], - OPTIONS, - ) + expect(codec.encodeError).toHaveBeenCalledWith(procedureError) }) it('reconciles errors thrown outside the procedure call with the procedure error map', async () => { diff --git a/packages/server/src/adapters/standard/handler.ts b/packages/server/src/adapters/standard/handler.ts index 5e83fc6c3..f0f263090 100644 --- a/packages/server/src/adapters/standard/handler.ts +++ b/packages/server/src/adapters/standard/handler.ts @@ -1,3 +1,4 @@ +import type { AnyORPCError } from '@orpc/client' import { ORPCError, toORPCError } from '@orpc/client' import type { ErrorMap, Schema } from '@orpc/contract' import { reconcileORPCError } from '@orpc/contract' @@ -68,6 +69,11 @@ export interface StandardHandlerRoutingInterceptorOptions< T extends Context, > extends ResolvedStandardHandlerHandleOptions { request: StandardLazyRequest + + /** + * Encodes an error the way procedure errors are encoded, to refuse a request with it. + */ + encodeError: (error: AnyORPCError) => Promisable } export type StandardHandlerRoutingInterceptor = Interceptor< StandardHandlerRoutingInterceptorOptions, @@ -120,6 +126,10 @@ export class StandardHandler { this.clientInterceptors = options.clientInterceptors } + encodeError(error: AnyORPCError): Promisable { + return this.codec.encodeError(error) + } + async handle( request: StandardLazyRequest, options: StandardHandlerHandleOptions, @@ -134,7 +144,7 @@ export class StandardHandler { return intercept( this.routingInterceptors, - { context, prefix, request }, + { context, prefix, request, encodeError: (error) => this.encodeError(error) }, async ({ context, prefix, request }) => { const span = getTracer()?.getActiveSpan() @@ -242,10 +252,7 @@ export class StandardHandler { ? error : await reconcileORPCError(procedure['~orpc'].errorMap, error) - const response = await this.codec.encodeError(reconciled, procedure, path, { - context, - prefix, - }) + const response = await this.codec.encodeError(reconciled) return { matched: true, response } } diff --git a/packages/server/src/adapters/standard/rpc-handler-codec.test.ts b/packages/server/src/adapters/standard/rpc-handler-codec.test.ts index 6bfb1e881..3064ab64c 100644 --- a/packages/server/src/adapters/standard/rpc-handler-codec.test.ts +++ b/packages/server/src/adapters/standard/rpc-handler-codec.test.ts @@ -205,7 +205,7 @@ describe('rpcHandlerCodec', () => { const codec = new RPCHandlerCodec(router, { serializer }) const error = new ORPCError('BAD_GATEWAY') - const response = codec.encodeError(error, procedure as any, ['ping'], options as any) + const response = codec.encodeError(error) expect(response).toEqual({ headers: {}, @@ -222,9 +222,7 @@ describe('rpcHandlerCodec', () => { const codec = new RPCHandlerCodec(router, { serializer }) const error = new ORPCError('toString' as any) - expect( - (await codec.encodeError(error, procedure as any, ['ping'], options as any)).status, - ).toEqual(DEFAULT_ERROR_STATUS) + expect((await codec.encodeError(error)).status).toEqual(DEFAULT_ERROR_STATUS) }) it('custom status with errorStatusCodes option', () => { @@ -242,12 +240,7 @@ describe('rpcHandlerCodec', () => { }) const overriddenError = new ORPCError('BAD_GATEWAY') - const overriddenResponse = codec.encodeError( - overriddenError, - procedure as any, - ['ping'], - options as any, - ) + const overriddenResponse = codec.encodeError(overriddenError) expect(overriddenResponse).toEqual({ headers: {}, @@ -256,12 +249,7 @@ describe('rpcHandlerCodec', () => { }) const unknownError = new ORPCError('UNKNOWN_CODE' as any) - const fallbackResponse = codec.encodeError( - unknownError, - procedure as any, - ['ping'], - options as any, - ) + const fallbackResponse = codec.encodeError(unknownError) expect(fallbackResponse).toEqual({ headers: {}, @@ -288,12 +276,7 @@ describe('rpcHandlerCodec', () => { }) const customizedError = new ORPCError('BAD_GATEWAY') - const customizedResponse = codec.encodeError( - customizedError, - procedure as any, - ['ping'], - options as any, - ) + const customizedResponse = codec.encodeError(customizedError) expect(customizedResponse).toEqual({ headers: {}, @@ -302,12 +285,7 @@ describe('rpcHandlerCodec', () => { }) const fallbackError = new ORPCError('UNKNOWN_ERROR') - const fallbackResponse = codec.encodeError( - fallbackError, - procedure as any, - ['ping'], - options as any, - ) + const fallbackResponse = codec.encodeError(fallbackError) expect(fallbackResponse).toEqual({ headers: {}, diff --git a/packages/server/src/adapters/standard/rpc-handler-codec.ts b/packages/server/src/adapters/standard/rpc-handler-codec.ts index 5aa227271..dacc242af 100644 --- a/packages/server/src/adapters/standard/rpc-handler-codec.ts +++ b/packages/server/src/adapters/standard/rpc-handler-codec.ts @@ -104,12 +104,7 @@ export class RPCHandlerCodec implements StandardHandlerCodec< } } - encodeError( - error: AnyORPCError, - _procedure: AnyProcedure, - _path: string[], - _options: ResolvedStandardHandlerHandleOptions, - ): Promisable { + encodeError(error: AnyORPCError): Promisable { const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS return { diff --git a/packages/server/src/adapters/standard/utils.ts b/packages/server/src/adapters/standard/utils.ts index afbfce86e..2f63b101f 100644 --- a/packages/server/src/adapters/standard/utils.ts +++ b/packages/server/src/adapters/standard/utils.ts @@ -1,3 +1,4 @@ +import { ORPCError } from '@orpc/client' import type { Promisable, Value } from '@orpc/shared' import type { StandardLazyRequest } from '@standard-server/core' @@ -20,3 +21,7 @@ export function resolveFriendlyStandardHandlerHandleOptions( context: options.context ?? ({} as T), // Context only optional if all fields are optional } } + +export function createNoProcedureMatchedError(): ORPCError<'NOT_FOUND', undefined> { + return new ORPCError('NOT_FOUND', { message: 'No procedure matched' }) +} diff --git a/packages/server/src/plugins/batch.test.ts b/packages/server/src/plugins/batch.test.ts index 0d49f8898..b368dc7e8 100644 --- a/packages/server/src/plugins/batch.test.ts +++ b/packages/server/src/plugins/batch.test.ts @@ -243,6 +243,9 @@ describe('batchHandlerPlugin', () => { expect(body).toHaveLength(1) expect(body[0]).toMatchObject({ kind: 'response', id: '0' }) expect(body[0].json.status).toBe(404) + expect(body[0].json.body).toEqual({ + json: { defined: false, code: 'NOT_FOUND', message: 'No procedure matched' }, + }) }) it('returns 400 for invalid batch body', async () => { @@ -255,7 +258,9 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.json()).toEqual({ + json: { defined: false, code: 'BAD_REQUEST', message: 'Invalid batch request' }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) @@ -271,7 +276,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }, ) @@ -288,11 +293,11 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }) - it('returns the ORPCError message a body plugin throws while resolving the batch body', async () => { + it('returns the ORPCError a body plugin throws while resolving the batch body', async () => { const handler = new RPCHandler(router, { plugins: [new BatchHandlerPlugin(), new RequestCompressionHandlerPlugin()], }) @@ -309,12 +314,18 @@ describe('batchHandlerPlugin', () => { }), ) - expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Too many content encodings.') + expect(response!.status).toBe(415) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'UNSUPPORTED_MEDIA_TYPE', + message: 'Too many content encodings.', + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) - it('returns the ORPCError message a body plugin raises while streaming the batch body', async () => { + it('returns the ORPCError a body plugin raises while streaming the batch body', async () => { const handler = new RPCHandler(router, { plugins: [new BatchHandlerPlugin(), new RequestLimitHandlerPlugin({ maxBodySize: 10 })], }) @@ -325,8 +336,42 @@ describe('batchHandlerPlugin', () => { }), ) - expect(response!.status).toBe(400) - expect(await response!.text()).toContain(new ORPCError('PAYLOAD_TOO_LARGE').message) + expect(response!.status).toBe(413) + expect(await response!.json()).toEqual({ + json: new ORPCError('PAYLOAD_TOO_LARGE').toJSON(), + }) + expect(handlerFn).toHaveBeenCalledTimes(0) + }) + + it('keeps the code, status, message and data of a custom error a body plugin raises', async () => { + const handler = new RPCHandler(router, { + plugins: [ + new BatchHandlerPlugin(), + new RequestLimitHandlerPlugin({ + maxBodySize: 10, + error: new ORPCError('TOO_MANY_REQUESTS', { + message: 'Slow down', + data: { limit: 10 }, + }), + }), + ], + }) + + const { response } = await handler.handle( + createBatchRequest({ + messages: [makePeerRequestMessage('0', '/ping')], + }), + ) + + expect(response!.status).toBe(429) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'TOO_MANY_REQUESTS', + message: 'Slow down', + data: { limit: 10 }, + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) @@ -344,9 +389,31 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(413) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'PAYLOAD_TOO_LARGE', + message: 'Batch request size exceeds the maximum allowed size', + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) + it('does not turn a failing maxSize option into a refusal', async () => { + const error = new Error('boom') + const handler = createHandler( + new BatchHandlerPlugin({ + maxSize: () => { + throw error + }, + }), + ) + + await expect( + handler.handle(createBatchRequest({ messages: [makePeerRequestMessage('0', '/ping')] })), + ).rejects.toBe(error) + }) + it('returns 500 sub-response when mapSubrequest throws', async ({ onTestFinished }) => { const rejectSpy = vi .spyOn(Promise, 'reject') @@ -374,7 +441,9 @@ describe('batchHandlerPlugin', () => { const body = (await response!.json()) as any expect(body[0].json.status).toBe(500) - expect(body[0].json.body).toBe('Internal server error') + expect(body[0].json.body).toEqual({ + json: new ORPCError('INTERNAL_SERVER_ERROR').toJSON(), + }) expect(rejectSpy).toHaveBeenCalledTimes(1) }) @@ -405,7 +474,9 @@ describe('batchHandlerPlugin', () => { const body = (await response!.json()) as any expect(body[0].json.status).toBe(500) - expect(body[0].json.body).toBe('Internal server error') + expect(body[0].json.body).toEqual({ + json: new ORPCError('INTERNAL_SERVER_ERROR').toJSON(), + }) expect(rejectSpy).toHaveBeenCalledTimes(1) }) @@ -722,7 +793,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') }) it.each(INVALID_MESSAGE_IDS)( @@ -741,7 +812,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }, ) @@ -760,7 +831,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }) diff --git a/packages/server/src/plugins/batch.ts b/packages/server/src/plugins/batch.ts index 306971d67..078c98c18 100644 --- a/packages/server/src/plugins/batch.ts +++ b/packages/server/src/plugins/batch.ts @@ -18,6 +18,7 @@ import { ServerPeer, } from '@standard-server/peer' +import { createNoProcedureMatchedError } from '../adapters/standard/index' import type { StandardHandlerOptions, StandardHandlerPlugin, @@ -71,17 +72,6 @@ function isClientPeerSendMessages(maybe: unknown): maybe is ClientPeerSendMessag ) } -/** - * Errors should not occur at the routing interceptor level. - * Reject the promise so it can be handled by the unhandledRejection handler - * for global logging or error handling. - */ -function internalError(err: unknown): StandardResponse { - void Promise.reject(err) - - return { status: 500, headers: {}, body: 'Internal server error' } -} - /** * What the batch needs from a subresponse before it answers, without keeping its body alive. */ @@ -337,83 +327,33 @@ export class BatchHandlerPlugin implements StandardHandlerPlu let messages: ClientPeerSendMessage[] try { - if (interceptorOptions.request.method === 'GET') { - const [, search] = parseStandardUrl(interceptorOptions.request.url) - const params = new URLSearchParams(search) - const data = params.getAll('data').at(-1) - - if (!data) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: 'Missing data parameter for batch request', - }, - } - } - - const mightBeMessages: unknown = JSON.parse(data) - - if (!isClientPeerSendMessages(mightBeMessages)) { - return { - matched: true, - response: { status: 400, headers: {}, body: 'Invalid batch request data parameter' }, - } - } - - messages = mightBeMessages - } else { - const mightBeMessages = await interceptorOptions.request.resolveBody() - - if (!isClientPeerSendMessages(mightBeMessages)) { - return { - matched: true, - response: { status: 400, headers: {}, body: 'Invalid batch request body' }, - } - } - - messages = mightBeMessages - } + messages = await this.readMessages(interceptorOptions.request) } catch (error) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: error instanceof ORPCError ? error.message : 'Invalid batch request', - }, - } + const refusal = + error instanceof ORPCError + ? error + : new ORPCError('BAD_REQUEST', { message: 'Invalid batch request', cause: error }) + + return { matched: true, response: await interceptorOptions.encodeError(refusal) } } - const outerMethod = interceptorOptions.request.method - if ( - (outerMethod === 'GET' || outerMethod === 'QUERY') && - messages.some( - (message) => message.kind === 'request' && message.json.method !== outerMethod, - ) - ) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: `${outerMethod} batch requests only accept ${outerMethod} sub-requests`, - }, - } + if (messages.length > (await value(this.maxSize, interceptorOptions))) { + const tooLarge = new ORPCError('PAYLOAD_TOO_LARGE', { + message: 'Batch request size exceeds the maximum allowed size', + }) + + return { matched: true, response: await interceptorOptions.encodeError(tooLarge) } } - const maxSize = await value(this.maxSize, interceptorOptions) + /** + * Errors should not occur at the routing interceptor level. + * Reject the promise so it can be handled by the unhandledRejection handler + * for global logging or error handling. + */ + const internalError = async (err: unknown): Promise => { + void Promise.reject(err) - if (messages.length > maxSize) { - return { - matched: true, - response: { - status: 413, - headers: {}, - body: 'Batch request size exceeds the maximum allowed size', - }, - } + return interceptorOptions.encodeError(new ORPCError('INTERNAL_SERVER_ERROR')) } const status = await value(this.successStatus, interceptorOptions) @@ -494,9 +434,9 @@ export class BatchHandlerPlugin implements StandardHandlerPlu const result = await interceptorOptions.next({ ...interceptorOptions, request }) response = result.matched ? result.response - : { status: 404, headers: {}, body: 'No procedure matched' } + : await interceptorOptions.encodeError(createNoProcedureMatchedError()) } catch (err) { - response = internalError(err) + response = await internalError(err) } markReady({ @@ -610,4 +550,38 @@ export class BatchHandlerPlugin implements StandardHandlerPlu routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)], } } + + private async readMessages(request: StandardLazyRequest): Promise { + let messages: unknown + + if (request.method === 'GET') { + const [, search] = parseStandardUrl(request.url) + const data = new URLSearchParams(search).getAll('data').at(-1) + + if (!data) { + throw new ORPCError('BAD_REQUEST', { message: 'Missing data parameter for batch request' }) + } + + messages = JSON.parse(data) + } else { + messages = await request.resolveBody() + } + + if (!isClientPeerSendMessages(messages)) { + throw new ORPCError('BAD_REQUEST', { message: 'Invalid batch request' }) + } + + if ( + (request.method === 'GET' || request.method === 'QUERY') && + messages.some( + (message) => message.kind === 'request' && message.json.method !== request.method, + ) + ) { + throw new ORPCError('BAD_REQUEST', { + message: `${request.method} batch requests only accept ${request.method} sub-requests`, + }) + } + + return messages + } } diff --git a/tests/batch/batch-plugin.test.ts b/tests/batch/batch-plugin.test.ts index 97f9d6b67..048312474 100644 --- a/tests/batch/batch-plugin.test.ts +++ b/tests/batch/batch-plugin.test.ts @@ -1,8 +1,15 @@ +import { createORPCClient } from '@orpc/client' +import { RPCLink } from '@orpc/client/fetch' +import { BatchLinkPlugin } from '@orpc/client/plugins' +import type { RouterClient } from '@orpc/server' import { ORPCError, os } from '@orpc/server' +import { RPCHandler } from '@orpc/server/fetch' +import { BatchHandlerPlugin, RequestLimitHandlerPlugin } from '@orpc/server/plugins' import { promiseWithResolvers } from '@orpc/shared' import { sleep } from '@standard-server/shared' import { z } from 'zod' +import { defaultBatchGroup } from './__shared__/client-server' import { createCompressionHonoFetchBatchClientServerTest } from './__shared__/client-server.compression-hono-fetch' import { createCompressionNodeHttpBatchClientServerTest } from './__shared__/client-server.compression-node-http' import { createHonoFetchBatchClientServerTest } from './__shared__/client-server.hono-fetch' @@ -268,3 +275,37 @@ describe('batch plugin: QUERY over node-http', () => { expect(fetchSpy.mock.calls[0]![1]).toEqual(expect.objectContaining({ method: 'QUERY' })) }) }) + +it('rejects every call with the error a plugin refused the batch body with', async () => { + const ping = vi.fn(async (_options: unknown, input: string) => input) + const router = { ping: os.input(z.string()).handler(ping) } + const handler = new RPCHandler(router, { + plugins: [ + new BatchHandlerPlugin(), + new RequestLimitHandlerPlugin({ + maxBodySize: 10, + error: new ORPCError('PAYLOAD_TOO_LARGE', { message: 'Too big', data: { max: 10 } }), + }), + ], + }) + const client: RouterClient = createORPCClient( + new RPCLink({ + url: '/rpc', + origin: 'http://localhost', + fetch: async (url, init) => (await handler.handle(new Request(url, init))).response!, + plugins: [new BatchLinkPlugin({ groups: [defaultBatchGroup] })], + }), + ) + + const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) + + for (const result of results) { + expect(result).toMatchObject({ + status: 'rejected', + reason: { code: 'PAYLOAD_TOO_LARGE', message: 'Too big', data: { max: 10 } }, + }) + expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) + } + + expect(ping).not.toHaveBeenCalled() +})