-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathgetAbsoluteUrl.ts
More file actions
46 lines (44 loc) · 1.55 KB
/
getAbsoluteUrl.ts
File metadata and controls
46 lines (44 loc) · 1.55 KB
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
import urijs, { QueryDataMap } from "urijs";
/**
* Join `url` with `baseUrl` if `url` is not an absolute (full) url string
*
* @export
* @param {string} url A full url string or a url path string (/a/b/c).
* @param {string} baseUrl A baseUrl used to generate a full url when a url path string is supplied via the `url` parameter.
* @param {QueryDataMap} [optionalQueries]
* @param {string[]} [allowedUrlHosts] Optional; when specify, the host of `url` parameter will only be used if it is included by this list.
* @returns
*/
export default function getAbsoluteUrl(
url: string,
baseUrl: string,
optionalQueries?: QueryDataMap,
allowedUrlHosts?: string[]
) {
const uri = urijs(url);
const urlHost = uri.host();
if (urlHost) {
// --- absolute url, return directly only if the urlHost is included by `allowedUrlHosts` (unless `allowedUrlHosts` is not supplied)
if (
!allowedUrlHosts ||
allowedUrlHosts.findIndex((item) => item === urlHost) !== -1
) {
return url;
}
}
// ignore url host of `host` if any and use `baseUrl` to create the final full url string
if (typeof baseUrl !== "string") {
baseUrl = "";
}
const baseUri = urijs(baseUrl);
const query = uri.search(true);
const mergedUri = baseUri.segmentCoded(
baseUri.segmentCoded().concat(uri.segmentCoded())
);
return mergedUri
.search({
...(query ? query : {}),
...(optionalQueries ? optionalQueries : {})
})
.toString();
}