Skip to content

Commit c87c54d

Browse files
committed
optimizing req URL parsing
1 parent 4b14de6 commit c87c54d

File tree

4 files changed

+85
-4
lines changed

4 files changed

+85
-4
lines changed

lib/router/sequential.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const Trouter = require('trouter')
2+
const qs = require('fast-querystring')
23
const next = require('./../next')
34

45
const status404 = {
@@ -36,10 +37,13 @@ module.exports = (config = {}) => {
3637
}
3738

3839
router.fetch = (req) => {
39-
const url = new URL(req.url)
40+
const url = req.url
41+
const startIndex = url.indexOf('/', 11)
42+
const queryIndex = url.indexOf('?', startIndex + 1)
43+
const path = queryIndex === -1 ? url.substring(startIndex) : url.substring(startIndex, queryIndex)
4044

41-
req.path = url.pathname || '/'
42-
req.query = url.queryparams
45+
req.path = path || '/'
46+
req.query = queryIndex > 0 ? qs.parse(url.substring(queryIndex + 1)) : {}
4347

4448
const match = router.find(req.method, req.path)
4549
if (match.handlers.length > 0) {

package-lock.json

Lines changed: 64 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"format": "bun x standard --fix"
99
},
1010
"dependencies": {
11+
"fast-querystring": "^1.1.2",
1112
"trouter": "^3.2.1"
1213
},
1314
"repository": {
@@ -21,7 +22,7 @@
2122
"lib/"
2223
],
2324
"devDependencies": {
24-
"0http-bun": "^1.0.0",
25+
"0http-bun": "^1.0.2",
2526
"mitata": "^0.1.11"
2627
},
2728
"keywords": [

test/smoke.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ describe('Router', () => {
1717
return Response.json(req.params)
1818
})
1919

20+
router.get('/qs', (req) => {
21+
return Response.json(req.query)
22+
})
23+
2024
router.delete('/get-params/:id', () => {
2125
return Response.json('OK')
2226
})
@@ -83,4 +87,12 @@ describe('Router', () => {
8387
expect(response.status).toBe(200)
8488
expect(await response.json()).toEqual({ engine: 'bun' })
8589
})
90+
91+
it('should return a JSON response with the query string parameters', async () => {
92+
const response = await router.fetch(new Request('http://localhost:3000/qs?foo=bar', {
93+
method: 'GET'
94+
}))
95+
expect(response.status).toBe(200)
96+
expect(await response.json()).toEqual({ foo: 'bar' })
97+
})
8698
})

0 commit comments

Comments
 (0)