forked from SamVerschueren/bragg-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.js
44 lines (34 loc) · 902 Bytes
/
route.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
'use strict';
const matcher = require('matcher');
function extractPathParams(path) {
const paramNames = [];
const regex = new RegExp('{(\\w+)}', 'g');
let res = regex.exec(path);
while (res !== null) {
paramNames.push(res[1]);
res = regex.exec(path);
}
return paramNames;
}
class Route {
constructor(path, methods, middleware, opts) {
this.path = path;
this.opts = opts || {};
this.methods = methods;
this.paramNames = [];
this.stack = Array.isArray(middleware) ? middleware : [middleware];
for (const fn of this.stack) {
const type = typeof fn;
if (type !== 'function') {
throw new Error(`${methods.toString()} \`${path}\`: middleware must be a function, not \`${type}\``);
}
}
if (!(path instanceof RegExp)) {
this.paramNames = extractPathParams(path);
}
}
match(path) {
return matcher.isMatch(path, this.path);
}
}
module.exports = Route;