Skip to content

Commit c1d7a4e

Browse files
committed
allow to disable router matching cache + perf improvements
1 parent 9288fcd commit c1d7a4e

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

lib/router/sequential.js

+28-9
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ module.exports = (config = {}) => {
1212
res.statusCode = 500
1313
res.end(err.message)
1414
})
15-
config.cacheSize = config.cacheSize || 1000
15+
if (config.cacheSize === undefined) {
16+
config.cacheSize = 1000
17+
}
1618
config.id = config.id || (Date.now().toString(36) + Math.random().toString(36).substr(2, 5)).toUpperCase()
1719

1820
const routers = {}
@@ -39,15 +41,29 @@ module.exports = (config = {}) => {
3941
}
4042

4143
router.lookup = (req, res, step) => {
42-
req.url = req.url || '/'
43-
req.originalUrl = req.originalUrl || req.url
44-
req.path = req.url.split('?')[0]
44+
if (!req.url) {
45+
req.url = '/'
46+
}
47+
if (!req.originalUrl) {
48+
req.originalUrl = req.url
49+
}
50+
const varsIndex = req.url.indexOf('?')
51+
if (varsIndex > 0) {
52+
req.path = req.url.slice(0, varsIndex)
53+
} else {
54+
req.path = req.url
55+
}
4556

46-
const reqCacheKey = `${req.method + req.path}`
47-
let match = cache.get(reqCacheKey)
48-
if (!match) {
57+
let match
58+
if (config.cacheSize > 0) {
59+
const reqCacheKey = `${req.method + req.path}`
60+
match = cache.get(reqCacheKey)
61+
if (!match) {
62+
match = router.find(req.method, req.path)
63+
cache.set(reqCacheKey, match)
64+
}
65+
} else {
4966
match = router.find(req.method, req.path)
50-
cache.set(reqCacheKey, match)
5167
}
5268

5369
if (match.handlers.length) {
@@ -66,7 +82,10 @@ module.exports = (config = {}) => {
6682
}
6783

6884
// middlewares invocation
69-
req.params = Object.assign(req.params || {}, match.params)
85+
if (!req.params) {
86+
req.params = {}
87+
}
88+
req.params = Object.assign(req.params, match.params)
7089

7190
return next(middlewares, req, res, 0, routers, config.defaultRoute, config.errorHandler)
7291
} else {

0 commit comments

Comments
 (0)