Registry Mirror
Skip to content

File tree

‎apps/content/docs/integrations/msw.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ const mock = createHTTPUtils(contract, {
117117
})
118118
```
119119

120-
The `context` option controls the [context](/docs/context) passed to the created handler on each request, and mock handlers receive it as `context`, enabling context-driven behaviors such as the [Response Headers Plugin](/docs/plugins/response-headers).
120+
The `context` option controls the [context](/docs/context) passed to the created handler on each request. It receives the MSW `request` and `cookies`, and mock handlers receive it as `context`, enabling context-driven behaviors such as the [Response Headers Plugin](/docs/plugins/response-headers).
121121

122122
```ts
123123
import {
@@ -156,7 +156,7 @@ const mock = createHTTPUtils(contract, {
156156
})
157157
```
158158

159-
Each mock serves a router containing only the procedure being mocked. Requests the created handler does not match simply fall through to other MSW handlers.
159+
Each mock serves a router containing only the procedure being mocked. Requests the created handler does not match simply fall through to other MSW handlers, or are reported as unhandled.
160160

161161
## Limitations
162162

‎packages/msw/src/http-procedure-utils.test.ts‎

Lines changed: 91 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type { AnyRouter } from '@orpc/server'
99
import { RPCHandler } from '@orpc/server/fetch'
1010
import type { ResponseHeadersHandlerPluginContext } from '@orpc/server/plugins'
1111
import { ResponseHeadersHandlerPlugin } from '@orpc/server/plugins'
12-
import { http, HttpResponse } from 'msw'
12+
import { getResponse, http, HttpResponse } from 'msw'
1313
import { setupServer } from 'msw/node'
1414
import * as z from 'zod'
1515

@@ -63,7 +63,7 @@ describe('handler', () => {
6363
expect(planet.discoveredAt).toBeInstanceOf(Date)
6464
})
6565

66-
it('exposes msw resolver info through the context option', async () => {
66+
it('exposes msw request info through the context option', async () => {
6767
const fn = vi.fn(({ input }: { input: { id: number } }) => ({
6868
id: input.id,
6969
name: 'Earth',
@@ -74,20 +74,61 @@ describe('handler', () => {
7474
origin: 'http://localhost:3000',
7575
prefix: '/rpc',
7676
// clone so the raw body stays readable after input deserialization
77-
context: (info) => ({ request: info.request.clone(), requestId: info.requestId }),
77+
context: (info) => ({ request: info.request.clone(), cookies: info.cookies }),
7878
handler: (router) => new RPCHandler(router),
7979
})
8080

8181
server.use(infoORPC.planet.find.handler(fn))
82-
await client.planet.find({ id: 1 })
82+
await fetch('http://localhost:3000/rpc/planet/find', {
83+
method: 'POST',
84+
headers: { 'content-type': 'application/json', 'cookie': 'session=abc' },
85+
body: JSON.stringify({ json: { id: 1 } }),
86+
})
8387

8488
const { context } = fn.mock.calls[0]![0] as any
8589
expect(context.request).toBeInstanceOf(Request)
8690
expect(context.request.url).toBe('http://localhost:3000/rpc/planet/find')
87-
expect(context.requestId).toBeTypeOf('string')
91+
expect(context.cookies).toEqual({ session: 'abc' })
8892
await expect(context.request.json()).resolves.toEqual({ json: { id: 1 } })
8993
})
9094

95+
it('responds with a response thrown from the context option', async () => {
96+
const throwingORPC = createHTTPUtils(contract, {
97+
origin: 'http://localhost:3000',
98+
prefix: '/rpc',
99+
context: () => {
100+
throw HttpResponse.text('denied', { status: 401 })
101+
},
102+
handler: (router) => new RPCHandler(router),
103+
})
104+
105+
const response = await getResponse(
106+
[throwingORPC.planet.list.handler(() => [])],
107+
new Request('http://localhost:3000/rpc/planet/list', { method: 'POST' }),
108+
)
109+
110+
expect(response?.status).toBe(401)
111+
await expect(response?.text()).resolves.toBe('denied')
112+
})
113+
114+
it('rethrows other errors thrown from the context option', async () => {
115+
const throwingORPC = createHTTPUtils(contract, {
116+
origin: 'http://localhost:3000',
117+
prefix: '/rpc',
118+
context: () => {
119+
throw new Error('context failed')
120+
},
121+
handler: (router) => new RPCHandler(router),
122+
})
123+
124+
await expect(
125+
getResponse(
126+
[throwingORPC.planet.list.handler(() => [])],
127+
new Request('http://localhost:3000/rpc/planet/list', { method: 'POST' }),
128+
),
129+
).rejects.toThrow('context failed')
130+
})
131+
91132
it('validates input like the real rpc handler', async () => {
92133
server.use(
93134
orpc.planet.find.handler(({ input }) => ({
@@ -282,6 +323,26 @@ describe('handler', () => {
282323
await expect(response.text()).resolves.toBe('fallback')
283324
})
284325

326+
it('resolves a relative origin against the msw base url', async () => {
327+
const relativeORPC = createHTTPUtils(contract, {
328+
origin: '',
329+
prefix: '/rpc',
330+
handler: (router) => new RPCHandler(router),
331+
})
332+
333+
const response = await getResponse(
334+
[relativeORPC.planet.list.handler(() => [])],
335+
new Request('http://localhost:3000/rpc/planet/list', { method: 'POST' }),
336+
{ baseUrl: 'http://localhost:3000' },
337+
)
338+
339+
await expect(response?.json()).resolves.toEqual({ json: [] })
340+
})
341+
342+
it('labels the handler with its url pattern', () => {
343+
expect(orpc.planet.list.handler(() => []).info.header).toContain('http://localhost:3000/rpc/*')
344+
})
345+
285346
it('leaves unmatched requests to other msw handlers', async () => {
286347
server.use(
287348
orpc.planet.list.handler(() => []),
@@ -293,6 +354,20 @@ describe('handler', () => {
293354

294355
await expect(response.text()).resolves.toBe('fallback')
295356
})
357+
358+
it('leaves requests for other procedures unhandled', async () => {
359+
const onUnhandled = vi.fn()
360+
server.events.on('request:unhandled', onUnhandled)
361+
362+
try {
363+
server.use(orpc.planet.list.handler(() => []))
364+
365+
await expect(client.planet.find({ id: 1 })).rejects.toThrow()
366+
expect(onUnhandled).toHaveBeenCalledTimes(1)
367+
} finally {
368+
server.events.removeListener('request:unhandled', onUnhandled)
369+
}
370+
})
296371
})
297372

298373
describe('error', () => {
@@ -336,33 +411,28 @@ describe('passthrough', () => {
336411
})
337412

338413
server.use(
339-
realORPC.planet.list.passthrough(),
340-
realORPC.planet.find.handler(({ input }) => ({
341-
id: input.id,
342-
name: 'Earth',
343-
discoveredAt: new Date('2020-01-01'),
344-
})),
414+
realORPC.planet.find.passthrough(),
415+
realORPC.planet.list.handler(() => [{ id: 1, name: 'Mars' }]),
345416
)
346417

347-
// the body must survive the matching attempt to reach the real server
348-
const response = await fetch(`http://localhost:${port}/rpc/planet/list`, {
418+
// matching reads the body to decode input, so it must not consume the original
419+
const body = JSON.stringify({ json: { id: 1 } })
420+
const response = await fetch(`http://localhost:${port}/rpc/planet/find`, {
349421
method: 'POST',
350-
body: '{}',
422+
headers: { 'content-type': 'application/json' },
423+
body,
351424
})
352425

353-
await expect(response.text()).resolves.toBe('real:{}')
426+
await expect(response.text()).resolves.toBe(`real:${body}`)
354427

355428
// other procedures fall through the passthrough handler and stay mocked
356-
const mocked = await fetch(`http://localhost:${port}/rpc/planet/find`, {
429+
const mocked = await fetch(`http://localhost:${port}/rpc/planet/list`, {
357430
method: 'POST',
358431
headers: { 'content-type': 'application/json' },
359-
body: JSON.stringify({ json: { id: 1 } }),
432+
body: '{}',
360433
})
361434

362-
await expect(mocked.json()).resolves.toEqual({
363-
json: { id: 1, name: 'Earth', discoveredAt: '2020-01-01T00:00:00.000Z' },
364-
meta: [['date', 'discoveredAt']],
365-
})
435+
await expect(mocked.json()).resolves.toEqual({ json: [{ id: 1, name: 'Mars' }] })
366436
} finally {
367437
realServer.close()
368438
}

‎packages/msw/src/http-procedure-utils.ts‎

Lines changed: 55 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import { implement } from '@orpc/server'
1212
import type { FetchHandler, FetchHandlerHandleResult } from '@orpc/server/fetch'
1313
import type { Promisable, Value } from '@orpc/shared'
1414
import { listenAbort, value } from '@orpc/shared'
15-
import type { HttpHandler, HttpRequestResolverExtras, PathParams, ResponseResolverInfo } from 'msw'
16-
import { http, passthrough } from 'msw'
15+
import type { HttpCustomPredicate, PathParams } from 'msw'
16+
import { HttpHandler, passthrough } from 'msw'
1717

1818
export type HTTPProcedureUtilsOptions<TContext extends Context> = ProcedureConfig & {
1919
/**
@@ -36,7 +36,8 @@ export type HTTPProcedureUtilsOptions<TContext extends Context> = ProcedureConfi
3636
* matched entirely by the created handler, so any protocol works.
3737
*
3838
* The router passed in contains only the procedure being mocked. Requests
39-
* the created handler does not match fall through to other MSW handlers.
39+
* the created handler does not match fall through to other MSW handlers,
40+
* or are reported as unhandled.
4041
*
4142
* @see {@link https://orpc.dev/docs/integrations/msw#advanced-configuration | MSW Integration - Advanced Configuration}
4243
*/
@@ -45,7 +46,7 @@ export type HTTPProcedureUtilsOptions<TContext extends Context> = ProcedureConfi
4546
? {
4647
/**
4748
* The context passed to the created handler for each request, resolved
48-
* with the MSW resolver information. Mock handlers receive it as
49+
* with the MSW request information. Mock handlers receive it as
4950
* `context`, enabling context-driven behaviors such as the Response
5051
* Headers Plugin.
5152
*
@@ -55,16 +56,13 @@ export type HTTPProcedureUtilsOptions<TContext extends Context> = ProcedureConfi
5556
* @see {@link https://orpc.dev/docs/integrations/msw#advanced-configuration | MSW Integration - Advanced Configuration}
5657
*/
5758
context?:
58-
| Value<
59-
Promisable<TContext>,
60-
[info: ResponseResolverInfo<HttpRequestResolverExtras<PathParams>>]
61-
>
59+
| Value<Promisable<TContext>, [info: Parameters<HttpCustomPredicate<PathParams>>[0]]>
6260
| undefined
6361
}
6462
: {
6563
/**
6664
* The context passed to the created handler for each request, resolved
67-
* with the MSW resolver information. Mock handlers receive it as
65+
* with the MSW request information. Mock handlers receive it as
6866
* `context`, enabling context-driven behaviors such as the Response
6967
* Headers Plugin.
7068
*
@@ -73,10 +71,7 @@ export type HTTPProcedureUtilsOptions<TContext extends Context> = ProcedureConfi
7371
*
7472
* @see {@link https://orpc.dev/docs/integrations/msw#advanced-configuration | MSW Integration - Advanced Configuration}
7573
*/
76-
context: Value<
77-
Promisable<TContext>,
78-
[info: ResponseResolverInfo<HttpRequestResolverExtras<PathParams>>]
79-
>
74+
context: Value<Promisable<TContext>, [info: Parameters<HttpCustomPredicate<PathParams>>[0]]>
8075
})
8176

8277
/**
@@ -92,11 +87,7 @@ export class HTTPProcedureUtils<
9287
TOutputSchema extends AnySchema,
9388
TErrorMap extends ErrorMap,
9489
> {
95-
/**
96-
* Matches every request under `origin` + `prefix`, the created fetch
97-
* handler decides whether a request targets this procedure.
98-
*/
99-
private readonly mswPathPredicate: string
90+
private readonly urlPattern: string
10091

10192
private readonly prefix: `/${string}` | undefined
10293

@@ -112,7 +103,7 @@ export class HTTPProcedureUtils<
112103
: `/${this.options.prefix.replace(/\/+$/, '').slice(1)}`
113104

114105
const base = `${origin}${this.prefix === undefined || this.prefix === '/' ? '' : this.prefix}`
115-
this.mswPathPredicate = base === '*' ? '*' : `${base}/*`
106+
this.urlPattern = base === '*' ? '*' : `${base}/*`
116107
}
117108

118109
/**
@@ -175,10 +166,6 @@ export class HTTPProcedureUtils<
175166
* @see {@link https://orpc.dev/docs/integrations/msw#passthrough | MSW Integration - Passthrough}
176167
*/
177168
passthrough(): HttpHandler {
178-
/**
179-
* A no-op implementation used purely to decide whether the request
180-
* targets this procedure, its response is discarded.
181-
*/
182169
const procedure = implement(this.contract, {
183170
disableInputValidation: true,
184171
disableOutputValidation: true,
@@ -198,10 +185,6 @@ export class HTTPProcedureUtils<
198185
private toMSWHandler(
199186
procedure: Router<TContext>,
200187
resolve: (result: FetchHandlerHandleResult) => Response | undefined,
201-
/**
202-
* Passthrough re-sends the original request to the real server, so the
203-
* matching attempt must consume a clone instead of the original.
204-
*/
205188
cloneRequest = false,
206189
): HttpHandler {
207190
const router = this.path.reduceRight<Router<TContext>>(
@@ -211,14 +194,9 @@ export class HTTPProcedureUtils<
211194

212195
const fetchHandler = this.options.handler(router)
213196

214-
return http.all(this.mswPathPredicate, async (info) => {
197+
return new ProcedureHttpHandler(this.urlPattern, async (info) => {
215198
const context = ((await value(this.options.context, info)) ?? {}) as TContext
216199

217-
/**
218-
* Matching never reads the body, so unmatched requests fall through
219-
* intact. Serving a matched request consumes the body like any MSW
220-
* resolver, clone the request in `context` if you need to read it.
221-
*/
222200
const result = await fetchHandler.handle(cloneRequest ? info.request.clone() : info.request, {
223201
prefix: this.prefix,
224202
context,
@@ -228,3 +206,47 @@ export class HTTPProcedureUtils<
228206
})
229207
}
230208
}
209+
210+
/**
211+
* Runs the fetch handler during MSW matching, so unmatched requests fall
212+
* through to other handlers or are reported as unhandled.
213+
*/
214+
class ProcedureHttpHandler extends HttpHandler {
215+
private readonly responses = new WeakMap<Request, Response>()
216+
217+
constructor(
218+
path: string,
219+
private readonly serve: (
220+
info: Parameters<HttpCustomPredicate<PathParams>>[0],
221+
) => Promise<Response | undefined>,
222+
) {
223+
super(/.+/, path, ({ request }) => this.responses.get(request))
224+
}
225+
226+
override async predicate(args: Parameters<HttpHandler['predicate']>[0]): Promise<boolean> {
227+
if (!(await super.predicate(args))) {
228+
return false
229+
}
230+
231+
/**
232+
* Like MSW resolvers, a thrown `Response` is used as the response.
233+
*/
234+
const response = await this.serve({
235+
request: args.request,
236+
cookies: args.parsedResult.cookies,
237+
}).catch((error) => {
238+
if (error instanceof Response) {
239+
return error
240+
}
241+
242+
throw error
243+
})
244+
245+
if (response === undefined) {
246+
return false
247+
}
248+
249+
this.responses.set(args.request, response)
250+
return true
251+
}
252+
}

0 commit comments

Comments
 (0)