Skip to content

Commit 11364dc

Browse files
committed
🔧 fix: NotFoundError should parse query if inferred
1 parent 22bf2c3 commit 11364dc

File tree

5 files changed

+76
-56
lines changed

5 files changed

+76
-56
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@ Bug fix:
1717
- [#1319](https://github.com/elysiajs/elysia/pull/1319) fix array of plugin usage causes incorrect path aggregation
1818
- [#1323](https://github.com/elysiajs/elysia/issues/1323) don't duplicate error from plugin
1919
- dynamic handle should handle named parser
20-
- hand
20+
- handle non-root additionalProperties
2121

2222
Improvement:
2323
- remove `finally` from compose
24+
- `NotFoundError` should parse query if inferred
2425

2526
Change:
2627
- afterResponse now call after response by scheduling setImmediate

example/a.ts

Lines changed: 46 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1+
// server.ts
12
import { Elysia, InternalServerError, t } from '../src'
2-
import { describe, it, expect, beforeEach } from 'bun:test'
3-
4-
let isOnResponseCalled: boolean
5-
let onResponseCalledCounter = 0
63

74
class CustomError extends Error {}
85

9-
const app = new Elysia({ aot: true })
10-
.onError(() => {
11-
6+
const app = new Elysia()
7+
.onAfterResponse((context) => {
8+
console.log(context.query)
129
})
13-
.onAfterResponse(() => {
14-
isOnResponseCalled = true
15-
onResponseCalledCounter++
16-
console.log(onResponseCalledCounter)
10+
.post('/', () => 'yay', {
11+
body: t.Object({
12+
test: t.String()
13+
})
1714
})
1815
.get('/customError', () => {
1916
throw new CustomError('whelp')
@@ -23,53 +20,49 @@ const app = new Elysia({ aot: true })
2320
})
2421
.listen(3000)
2522

26-
// console.log(app.routes[0].compile().toString())
27-
// console.log(app.handleError.toString())
28-
29-
app.handle(new Request('http://localhost/customError'))
30-
31-
// beforeEach(() => {
32-
// isOnResponseCalled = false
33-
// onResponseCalledCounter = 0
34-
// })
23+
console.log(app.server!.url.toString())
3524

25+
// client.ts
3626
export const newReq = (params?: {
3727
path?: string
3828
headers?: Record<string, string>
3929
method?: string
4030
body?: string
41-
}) => new Request(`http://localhost${params?.path ?? '/'}`, params)
42-
43-
// describe('Error', () => {
44-
// it.each([
45-
// ['NotFoundError', newReq({ path: '/notFound' })],
46-
// [
47-
// 'ParseError',
48-
// newReq({
49-
// method: 'POST',
50-
// headers: { 'Content-Type': 'application/json' },
51-
// body: ''
52-
// })
53-
// ],
54-
// [
55-
// 'ValidationError',
56-
// newReq({
57-
// method: 'POST',
58-
// headers: { 'Content-Type': 'application/json' },
59-
// body: JSON.stringify({})
60-
// })
61-
// ],
62-
// ['CustomError', newReq({ path: '/customError' })],
63-
// ['InternalServerError', newReq({ path: '/internalError' })]
64-
// ])('%s should call onResponse', async (_name, request) => {
65-
// expect(isOnResponseCalled).toBeFalse()
66-
// expect(onResponseCalledCounter).toBe(0)
67-
// await app.handle(request)
31+
query: string
32+
}) =>
33+
new Request(
34+
`http://localhost:3000${params?.path ?? '/'}?name=${params?.query}`,
35+
params
36+
)
6837

69-
// // wait for next tick
70-
// await Bun.sleep(1)
38+
const cases = [
39+
['NotFoundError', newReq({ path: '/notFound', query: 'NotFoundError' })],
40+
[
41+
'ParseError',
42+
newReq({
43+
method: 'POST',
44+
headers: { 'Content-Type': 'application/json' },
45+
body: '',
46+
query: 'ParseError'
47+
})
48+
],
49+
[
50+
'ValidationError',
51+
newReq({
52+
method: 'POST',
53+
headers: { 'Content-Type': 'application/json' },
54+
body: JSON.stringify({}),
55+
query: 'ValidationError'
56+
})
57+
],
58+
['CustomError', newReq({ path: '/customError', query: 'CustomError' })],
59+
[
60+
'InternalServerError',
61+
newReq({ path: '/internalError', query: 'InternalServerError' })
62+
]
63+
] as const
7164

72-
// expect(isOnResponseCalled).toBeTrue()
73-
// expect(onResponseCalledCounter).toBe(1)
74-
// })
75-
// })
65+
for (const [name, req] of cases) {
66+
console.log("N", name)
67+
await fetch(req)
68+
}

src/adapter/web-standard/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,9 @@ export const WebStandardAdapter: ElysiaAdapter = {
128128
},
129129
error404(hasEventHook, hasErrorHook, afterHandle = '') {
130130
let findDynamicRoute =
131-
`if(route===null){` + afterHandle + '\nreturn '
131+
`if(route===null){` +
132+
afterHandle +
133+
'\nreturn '
132134

133135
if (hasErrorHook)
134136
findDynamicRoute += `app.handleError(c,notFound,false,${this.parameters})`

src/compose.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2254,7 +2254,7 @@ export const composeGeneralHandler = (app: AnyElysia) => {
22542254

22552255
findDynamicRoute += router.http.root.ALL ? '??router.find("ALL",p)\n' : '\n'
22562256

2257-
let afterResponse = ''
2257+
let afterResponse = `c.error=notFound\n`
22582258
if (app.event.afterResponse?.length) {
22592259
const prefix = app.event.afterResponse.some(isAsync) ? 'async' : ''
22602260
afterResponse += `\nsetImmediate(${prefix}()=>{`
@@ -2268,6 +2268,15 @@ export const composeGeneralHandler = (app: AnyElysia) => {
22682268
afterResponse += `})\n`
22692269
}
22702270

2271+
// @ts-ignore
2272+
if (app.inference.query)
2273+
afterResponse +=
2274+
'if(c.qi===-1){' +
2275+
'c.query={}' +
2276+
'}else{' +
2277+
'c.query=parseQueryFromURL(c.url,c.qi+1)' +
2278+
'}'
2279+
22712280
const error404 = adapter.error404(
22722281
!!app.event.request?.length,
22732282
!!app.event.error?.length,
@@ -2334,6 +2343,8 @@ export const composeGeneralHandler = (app: AnyElysia) => {
23342343
`handleError,` +
23352344
`status,` +
23362345
`redirect,` +
2346+
// @ts-ignore
2347+
allocateIf(`parseQueryFromURL,`, app.inference.query) +
23372348
allocateIf(`ELYSIA_TRACE,`, hasTrace) +
23382349
allocateIf(`ELYSIA_REQUEST_ID,`, hasTrace) +
23392350
adapterVariables +
@@ -2397,6 +2408,8 @@ export const composeGeneralHandler = (app: AnyElysia) => {
23972408
handleError,
23982409
status,
23992410
redirect,
2411+
// @ts-ignore
2412+
parseQueryFromURL: app.inference.query ? parseQueryFromURL : undefined,
24002413
ELYSIA_TRACE: hasTrace ? ELYSIA_TRACE : undefined,
24012414
ELYSIA_REQUEST_ID: hasTrace ? ELYSIA_REQUEST_ID : undefined,
24022415
...adapter.inject

test/lifecycle/error.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,4 +330,15 @@ describe('error', () => {
330330
expect(await response.text()).toBe('Unauthorized')
331331
expect(i).toBe(1)
332332
})
333+
334+
it('404 should parse query if infer', async () => {
335+
const app = new Elysia().onError(({ query }) => query)
336+
337+
const response = await app.handle(
338+
new Request('http://localhost?hello=world')
339+
)
340+
341+
expect(response.status).toBe(404)
342+
expect(await response.json()).toEqual({ hello: 'world' })
343+
})
333344
})

0 commit comments

Comments
 (0)