From 086443aeccf200b086fbdd6a37758d0deb1cc380 Mon Sep 17 00:00:00 2001 From: Rolando Santamaria Maso Date: Sat, 6 Apr 2024 10:23:52 +0200 Subject: [PATCH] improving performance --- lib/next.js | 7 ++++--- lib/router/sequential.js | 4 ++-- lib/utils/queryparams.js | 20 ++++++++++++-------- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/lib/next.js b/lib/next.js index aeadfc2..bc560cb 100644 --- a/lib/next.js +++ b/lib/next.js @@ -1,8 +1,7 @@ function next (middlewares, req, res, index, routers, defaultRoute, errorHandler) { routers = routers || {} - const middleware = middlewares[index] - if (!middleware) { + if (index >= middlewares.length) { if (!res.finished) { return defaultRoute(req, res) } @@ -10,11 +9,13 @@ function next (middlewares, req, res, index, routers, defaultRoute, errorHandler return } + const middleware = middlewares[index++] + function step (err) { if (err) { return errorHandler(err, req, res) } else { - return next(middlewares, req, res, index + 1, routers, defaultRoute, errorHandler) + return next(middlewares, req, res, index, routers, defaultRoute, errorHandler) } } diff --git a/lib/router/sequential.js b/lib/router/sequential.js index 88edbef..538e53b 100644 --- a/lib/router/sequential.js +++ b/lib/router/sequential.js @@ -1,6 +1,6 @@ const Trouter = require('trouter') const next = require('./../next') -const LRU = require('lru-cache') +const { LRUCache: LRU } = require('lru-cache') const { parse } = require('regexparam') const queryparams = require('../utils/queryparams') @@ -70,7 +70,7 @@ module.exports = (config = {}) => { match = router.find(req.method, req.path) } - if (match.handlers.length !== 0) { + if (match.handlers.length > 0) { const middlewares = [...match.handlers] if (step !== undefined) { // router is being used as a nested router diff --git a/lib/utils/queryparams.js b/lib/utils/queryparams.js index f3f7f29..f2b68fc 100644 --- a/lib/utils/queryparams.js +++ b/lib/utils/queryparams.js @@ -1,13 +1,17 @@ module.exports = (req, url) => { - const [path, search = ''] = url.split('?') - const searchParams = new URLSearchParams(search.replace(/\[\]=/g, '=')) - const query = {} - for (const [name, value] of searchParams.entries()) { - if (query[name]) { - Array.isArray(query[name]) ? query[name].push(value) : (query[name] = [query[name], value]) - } else { - query[name] = value + const indexOfQuestionMark = url.indexOf('?'); + const path = indexOfQuestionMark !== -1 ? url.slice(0, indexOfQuestionMark) : url; + const search = indexOfQuestionMark !== -1 ? url.slice(indexOfQuestionMark + 1) : ''; + + if (search.length > 0) { + const searchParams = new URLSearchParams(search.replace(/\[\]=/g, '=')) + for (const [name, value] of searchParams.entries()) { + if (query[name]) { + Array.isArray(query[name]) ? query[name].push(value) : (query[name] = [query[name], value]) + } else { + query[name] = value + } } }