-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
37 lines (32 loc) · 1.16 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
let shortUrl;
function shortener(url) {
// Checking if the url is valid or not
function validURL(str) {
const pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
return !!pattern.test(str);
}
const checkUrl = validURL(url);
// If the url is valid then we will send a request to the server
if (!checkUrl) return "Invalid URL";
if (checkUrl) {
async function shortIt(url) {
const response = await fetch(`https://api.shrtco.de/v2/shorten?url=${url}`);
const data = await response.json();
shortUrl = data.result.full_short_link;
return shortUrl;
}
const short = shortIt(url).then((result) => {
return result;
});
return short;
}
}
export default shortener;