-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (41 loc) · 1.1 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
// @ts-check
const pathToRegexp = require('path-to-regexp')
/**
* @typedef {(request: { params: any, pathname: string, search: string}) => any} RouteHandler
* @typedef {{ regex: RegExp, keys: { name: string }[], handler: RouteHandler }} Route
*/
function Router () {
const self = Object.assign(render, { use })
/**
* @type {Route[]}
*/
const routes = []
/**
* @param {string} route
* @param {RouteHandler} handler
*/
function use (route, handler) {
const keys = []
const regex = pathToRegexp(route, keys, null)
routes.push({ regex, keys, handler })
return self
}
/**
* @param {{pathname: string, search: string}} location
*/
function render (location) {
for (const route of routes) {
const result = route.regex.exec(location.pathname)
if (result) {
const params = result.slice(1).reduce((params, match, index) => {
const key = route.keys[index]
params[key.name] = match
return params
}, {})
return route.handler({ params, ...location })
}
}
}
return self
}
module.exports = Router