diff --git a/src/withParams.spec.ts b/src/withParams.spec.ts index 3f109ad..7b8f42d 100644 --- a/src/withParams.spec.ts +++ b/src/withParams.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Router } from './Router' import { withParams } from './withParams' +import { toReq } from '../lib/index' describe('withParams (middleware)', () => { it('allows accessing route params from the request itself', async () => { @@ -69,4 +70,14 @@ describe('withParams (middleware)', () => { testParam: 'testValue', }) }) + + it('downstream handlers can access original Request through request.raw', async () => { + const handler = vi.fn(r => r.raw) + const router = Router().get('/', withParams, handler) + const request = toReq('/') + + await router.fetch(request) + + expect(handler).toHaveReturnedWith(request) + }) }) diff --git a/src/withParams.ts b/src/withParams.ts index 2388a88..588c645 100644 --- a/src/withParams.ts +++ b/src/withParams.ts @@ -1,9 +1,11 @@ import { IRequest } from './types' export const withParams = (request: IRequest): void => { - request.proxy = new Proxy(request.proxy || request, { - get: (obj, prop) => obj[prop] !== undefined - ? obj[prop]?.bind?.(request) || obj[prop] - : obj?.params?.[prop] + request.raw = request.raw ?? request // places reference to request in request.raw if safe to do so + request.proxy = new Proxy(request.proxy ?? request, { + get: (obj, prop, receiver) => + obj[prop]?.bind?.(request) // if prop exists (as function), return the function, bound to the original request + ?? obj[prop] // if prop exists, return it + ?? obj?.params?.[prop] // if no prop exists, try the params object }) }