This repository has been archived by the owner on Nov 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
47 lines (37 loc) · 1.42 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
'use strict';
module.exports = reversePath;
// regex from https://github.com/component/path-to-regexp
var PATH_REGEXP = new RegExp([
// Match already escaped characters that would otherwise incorrectly appear
// in future matches. This allows the user to escape special characters that
// shouldn't be transformed.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?',
// Match regexp special characters that should always be escaped.
'([.+*?=^!:${}()[\\]|\\/])'
].join('|'), 'g');
function reversePath(path, params, options) {
var index = 0;
params = params || {};
options = options || {};
return path.replace(PATH_REGEXP, replace);
function replace(match, escaped, prefix, key, capture, group, optional, escape) {
if(escaped) return escaped;
if(escape) return escape;
prefix = prefix || '';
var value = params[key || index++];
if(value === undefined) {
if(optional) {
value = '';
} else {
throw new Error('Parameter "' + key + '" is required.');
}
}
return prefix + value;
}
}