-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathnext.js
More file actions
61 lines (52 loc) · 1.86 KB
/
next.js
File metadata and controls
61 lines (52 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Optimized middleware executor
*
* @param {Array} middlewares - Array of middleware functions
* @param {Object} req - Request object
* @param {Object} res - Response object
* @param {Number} index - Current middleware index
* @param {Object} routers - Router patterns map
* @param {Function} defaultRoute - Default route handler
* @param {Function} errorHandler - Error handler
* @returns {*} Result of middleware execution
*/
function next (middlewares, req, res, index, routers, defaultRoute, errorHandler) {
// Fast path for end of middleware chain
if (index >= middlewares.length) {
// Only call defaultRoute if response is not finished
return !res.finished && defaultRoute(req, res)
}
// Get current middleware and increment index
const middleware = middlewares[index++]
// Create step function - this is called by middleware to continue the chain
const step = function (err) {
return err
? errorHandler(err, req, res)
: next(middlewares, req, res, index, routers, defaultRoute, errorHandler)
}
try {
// Check if middleware is a router (has id)
if (middleware.id) {
// Get pattern for nested router
const pattern = routers?.[middleware.id]
if (pattern) {
// Save original URL and path
req.preRouterUrl = req.url
req.preRouterPath = req.path
// Replace pattern in URL - this is a hot path, optimize it
req.url = req.url.replace(pattern, '')
// Ensure URL starts with a slash
if (req.url.length === 0 || req.url.charCodeAt(0) !== 47) { // 47 is '/'
req.url = '/' + req.url
}
}
// Call router's lookup method
return middleware.lookup(req, res, step)
}
// Regular middleware function
return middleware(req, res, step)
} catch (err) {
return errorHandler(err, req, res)
}
}
module.exports = next