-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (68 loc) · 2.09 KB
/
index.js
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
const handlers = {
match: updateParams => (req, res, params) => {
if (updateParams) {
req.params = params
}
return true
},
default: () => false
}
module.exports = function (routerOpts = {}, routerFactory = require('find-my-way')) {
routerOpts.defaultRoute = handlers.default
function exec (options, isIff = true) {
const middleware = this
// independent router instance per config
const router = routerFactory(routerOpts)
const opts = typeof options === 'function' ? { custom: options } : (Array.isArray(options) ? { endpoints: options } : options)
if (opts.endpoints && opts.endpoints.length) {
// setup matching router
opts.endpoints
.map(endpoint => typeof endpoint === 'string' ? { url: endpoint } : endpoint)
.forEach(({ methods = ['GET'], url, version, updateParams = false }) => {
if (version) {
router.on(methods, url, { constraints: { version } }, handlers.match(updateParams))
} else {
router.on(methods, url, handlers.match(updateParams))
}
})
}
const result = function (req, res, next) {
// supporting custom matching function
if (opts.custom) {
if (opts.custom(req)) {
if (isIff) {
return middleware(req, res, next)
}
} else if (!isIff) {
return middleware(req, res, next)
}
// leave here and do not process opts.endpoints
return next()
}
// matching endpoints and moving forward
if (router.lookup(req, res)) {
if (isIff) {
return middleware(req, res, next)
}
} else if (!isIff) {
return middleware(req, res, next)
}
return next()
}
// allowing 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
}
}