-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
112 lines (91 loc) · 2.8 KB
/
index.js
File metadata and controls
112 lines (91 loc) · 2.8 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Optimized handlers with minimal allocations
const createMatchHandler = (updateParams) =>
updateParams
? (req, res, params) => {
req.params = params
return true
}
: () => true
const defaultHandler = () => false
// Router cache for reusing router instances
const routerCache = new WeakMap()
function normalizeEndpoint (endpoint) {
if (typeof endpoint === 'string') {
return { url: endpoint, methods: ['GET'], updateParams: false }
}
return {
methods: endpoint.methods || ['GET'],
url: endpoint.url,
version: endpoint.version,
updateParams: endpoint.updateParams || false
}
}
module.exports = function (routerOpts = {}, routerFactory = require('find-my-way')) {
function exec (options, isIff = true) {
const middleware = this
let router = null
let customFn = null
// Process options efficiently
if (typeof options === 'function') {
customFn = options
} else {
const endpoints = Array.isArray(options) ? options : options?.endpoints
if (endpoints?.length) {
// Try to get cached router first
let cache = routerCache.get(routerOpts)
if (!cache) {
cache = new Map()
routerCache.set(routerOpts, cache)
}
const cacheKey = JSON.stringify(endpoints)
router = cache.get(cacheKey)
if (!router) {
router = routerFactory({ ...routerOpts, defaultRoute: defaultHandler })
// Normalize and register routes
const normalized = endpoints.map(normalizeEndpoint)
for (const { methods, url, version, updateParams } of normalized) {
const handler = createMatchHandler(updateParams)
if (version) {
router.on(methods, url, { constraints: { version } }, handler)
} else {
router.on(methods, url, handler)
}
}
cache.set(cacheKey, router)
}
}
if (options?.custom) {
customFn = options.custom
}
}
// Optimized execution function
const result = function (req, res, next) {
let shouldExecute = false
if (customFn) {
shouldExecute = customFn(req)
} else if (router) {
shouldExecute = router.lookup(req, res)
}
// Simplified logic: execute middleware if conditions match
if ((isIff && shouldExecute) || (!isIff && !shouldExecute)) {
return middleware(req, res, next)
}
return next()
}
// Allow chaining
result.iff = iff
result.unless = unless
return result
}
function iff (options) {
return exec.call(this, options, true)
}
function unless (options) {
return exec.call(this, options, false)
}
return function (middleware) {
middleware.iff = iff
middleware.unless = unless
return middleware
}
}