-
Notifications
You must be signed in to change notification settings - Fork 483
Expand file tree
/
Copy pathshorten-url.ts
More file actions
65 lines (55 loc) · 1.81 KB
/
Copy pathshorten-url.ts
File metadata and controls
65 lines (55 loc) · 1.81 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { PROFILER_SERVER_ORIGIN } from 'firefox-profiler/app-logic/constants';
const ACCEPT_HEADER_VALUE = 'application/vnd.firefox-profiler+json;version=1.0';
export async function shortenUrl(urlToShorten: string): Promise<string> {
let longUrl = urlToShorten;
if (!longUrl.startsWith('https://profiler.firefox.com/')) {
const parsedUrl = new URL(longUrl);
parsedUrl.protocol = 'https';
parsedUrl.host = 'profiler.firefox.com';
parsedUrl.port = '';
longUrl = parsedUrl.toString();
}
const ENDPOINT = `${PROFILER_SERVER_ORIGIN}/shorten`;
const payload = {
longUrl,
};
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
Accept: ACCEPT_HEADER_VALUE,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(
`An error happened while shortening the long url ${longUrl}: ${response.statusText} (${response.status})`
);
}
const json = await response.json();
return json.shortUrl;
}
export async function expandUrl(shortUrl: string): Promise<string> {
const ENDPOINT = `${PROFILER_SERVER_ORIGIN}/expand`;
const payload = {
shortUrl,
};
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
Accept: ACCEPT_HEADER_VALUE,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(
`An error happened while expanding the shortened url ${shortUrl}: ${response.statusText} (${response.status})`
);
}
const json = await response.json();
return json.longUrl;
}