From 2d1a274703b52ddb3f96fd1df1e82392416071ce Mon Sep 17 00:00:00 2001 From: Kevin Whitley Date: Sun, 7 Apr 2024 14:30:56 -0500 Subject: [PATCH] withParams refactor and test --- src/withParams.spec.ts | 11 +++++++++++ src/withParams.ts | 10 ++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/withParams.spec.ts b/src/withParams.spec.ts index 3f109ad6..7b8f42d1 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 2388a883..588c645d 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 }) }