From 9c669c8fa3203f5fa58aee1b97b291ce26bf0ada Mon Sep 17 00:00:00 2001 From: Rolando Santamaria Maso Date: Sun, 26 Jan 2025 11:11:24 +0100 Subject: [PATCH] introducing router matching cache --- lib/router/sequential.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/router/sequential.js b/lib/router/sequential.js index 93c55eb..f11a139 100644 --- a/lib/router/sequential.js +++ b/lib/router/sequential.js @@ -10,6 +10,8 @@ const STATUS_500 = { } module.exports = (config = {}) => { + const cache = new Map() + if (!config.defaultRoute) { config.defaultRoute = () => { return new Response(null, STATUS_404) @@ -45,8 +47,16 @@ module.exports = (config = {}) => { req.path = path || '/' req.query = queryIndex > 0 ? qs.parse(url.substring(queryIndex + 1)) : {} - const match = router.find(req.method, req.path) - if (match.handlers.length > 0) { + const cacheKey = `${req.method}:${req.path}` + let match = null + if (cache.has(cacheKey)) { + match = cache.get(cacheKey) + } else { + match = router.find(req.method, req.path) + cache.set(cacheKey, match) + } + + if (match?.handlers?.length > 0) { if (!req.params) { req.params = {} }