-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
61 lines (55 loc) · 1.28 KB
/
index.ts
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
import * as axios from "axios";
import { parseStringPromise } from "xml2js";
export interface ShortLinkParam {
username: string;
password: string;
serverUrl: string;
url: string;
}
export interface YourlsResponse {
root: {
status: string[];
code: string[];
message: string[];
errorCode: string[];
statusCode: string[];
url: Array<null[]>;
title: string[];
shorturl: string[];
};
}
async function parseXml(input: string) {
try {
return parseStringPromise(input);
} catch (err: any) {
console.error(input);
throw new Error(
"Error encountered while parsing the XML, Error:" + err.message
);
}
}
export async function getShortLink({
username,
password,
url,
serverUrl,
}: ShortLinkParam): Promise<YourlsResponse> {
try {
const response = await axios.default.get<string>(
`${serverUrl}?username=${username}&password=${password}&action=shorturl&url=${url}`,
{
headers: {
"Content-Type": "text/xml",
},
}
);
return parseXml(response.data);
} catch (err: any) {
if (err instanceof axios.AxiosError) {
return parseXml(err.response?.data);
}
throw Error(
"We encountered a non axios error, perhaps there is a problem with XML response."
);
}
}