-
Notifications
You must be signed in to change notification settings - Fork 2
/
expandUrl.js
43 lines (36 loc) · 1.19 KB
/
expandUrl.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
var extend = require('./extend')
var parseUri = require('./parseUri')
var querystringLite = require('./querystring-lite')
module.exports = function expandUrl (pattern, _params, _qs) {
var qs = _qs || querystringLite
var params = _params || {}
var onlyQueryParams = extend({}, params)
var uri = parseUri(pattern)
var pathPattern = uri.pathname
var path = pathPattern.replace(/:([a-z_][a-z0-9_]*)\*/gi, function (_, id) {
var param = params[id]
if (param === undefined) {
throw new Error('No value for :' + id + '*')
}
delete onlyQueryParams[id]
return encodeURI(paramToString(param))
})
path = path.replace(/:([a-z_][a-z0-9_]*)/gi, function (_, id) {
var param = params[id]
if (param === undefined) {
throw new Error('No value for :' + id)
}
delete onlyQueryParams[id]
return encodeURIComponent(paramToString(param))
})
var query = qs.stringify(extend(qs.parse(uri.search.replace(/^\?/, '')), onlyQueryParams))
var fullpath = query ? path + '?' + query : path
return uri.protocol + uri.authority + fullpath + uri.hash
}
function paramToString (p) {
if (p === undefined || p === null) {
return ''
} else {
return p
}
}