Skip to content

Commit

Permalink
withParams refactor and test
Browse files Browse the repository at this point in the history
  • Loading branch information
kwhitley committed Apr 7, 2024
1 parent 4c4f413 commit 2d1a274
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 11 additions & 0 deletions src/withParams.spec.ts
Original file line number Diff line number Diff line change
@@ -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 () => {
Expand Down Expand Up @@ -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)
})
})
10 changes: 6 additions & 4 deletions src/withParams.ts
Original file line number Diff line number Diff line change
@@ -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
})
}

0 comments on commit 2d1a274

Please sign in to comment.