blob: ca685c5795604af196b694684008719567722d6c (
plain)
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
|
interface ShortenResponse {
hash: string;
}
export interface ShortenRequest {
url: string;
nonce: string;
response: Promise<ShortenResponse>;
}
async function makeRequest(url: string): Promise<ShortenResponse> {
let body;
try {
const response = await fetch("/", {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
method: "post",
body: JSON.stringify({ url }),
});
body = await response.json();
} catch (err) {
throw {
error: "Error!",
};
}
if (body.hash) {
return {
hash: body.hash,
};
} else {
throw {
message: body.error || "Error!",
};
}
}
export default function shorten(url: string): ShortenRequest {
const nonce = Math.random().toString(36).substr(2, 5);
return {
url,
nonce,
response: makeRequest(url),
};
}
|