-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
63 lines (50 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict'
/**
* Module dependencies.
*/
const debug = require('debug')('koa-rewrite')
const { pathToRegexp } = require('path-to-regexp')
/**
* Rwrite `src` to `dst`.
*
* @param {String|RegExp} src
* @param {String} dst
* @return {Function}
* @api public
*/
module.exports = function rewrite (src, dst) {
const keys = []
const re = pathToRegexp(src, keys)
const map = toMap(keys)
debug('rewrite %s -> %s %s', src, dst, re)
return function (ctx, next) {
const orig = ctx.url
const m = re.exec(orig)
if (m) {
ctx.url = dst.replace(/\$(\d+)|(?::(\w+))/g, (_, n, name) => {
if (name) return m[map[name].index + 1] || ''
return m[n] || ''
})
debug('rewrite %s -> %s', orig, ctx.url)
return next().then(() => {
ctx.url = orig
})
}
return next()
}
}
/**
* Turn params array into a map for quick lookup.
*
* @param {Array} params
* @return {Object}
* @api private
*/
function toMap (params) {
const map = {}
params.forEach((param, i) => {
param.index = i
map[param.name] = param
})
return map
}