-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathrequest.ts
95 lines (86 loc) · 2.75 KB
/
request.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import logger from 'common/logger';
import * as xml2js from 'xml2js';
import errors from './requestErrors';
interface RequestOptions {
url: string;
query?: Record<string, string | number | string[]>;
body?: object | string;
headers?: HeadersInit;
username?: string;
password?: string;
type?: string;
timeout?: number;
}
type LinkHeader = Record<string, string> | undefined;
interface RequestResponse {
body: any;
headers: Headers;
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
// example: { next: 'http://example.com/page/2' }
links: LinkHeader;
}
const get = async (options: RequestOptions): Promise<RequestResponse> => {
const url: URL = new URL(options.url);
Object.entries(options.query ?? {}).forEach(([key, value]) => {
url.searchParams.append(key, value as string);
});
const fetchOptions = createRequest(options);
const response = await fetch(url, fetchOptions);
logger.log('request.fetch', fetchOptions, response);
if (!response.ok) {
logger.info('Request failed', errors.create(response, options.url));
throw errors.create(response, options.url);
}
try {
const data =
options.type === 'xml' ? await parseXml(response) : await response.json();
return {
body: data,
headers: response.headers,
links: parseLinks(response.headers),
};
} catch (ex: any) {
throw new Error(`${ex.message} (${options.url})`);
}
};
export default {
get,
};
const parseLinks = (headers: Headers): LinkHeader => {
const linkHeader = headers.get('Link');
if (!linkHeader) return undefined;
const links: LinkHeader = {};
const matches = linkHeader.matchAll(/<(.+?)>;\s*rel="(.+?)"/g);
for (const match of matches) {
const [, url, rel] = match;
links[rel] = new URL(url).href;
}
return links;
};
function createRequest(options: RequestOptions) {
const headers = new Headers(options.headers);
if (options.username) {
headers.set(
'Authorization',
'Basic ' + btoa(`${options.username}:${options.password ?? ''}`),
);
}
if (options.type) {
headers.set('Content-Type', `application/${options.type}`);
headers.set('Accept', `application/${options.type}`);
}
return {
method: 'GET',
headers,
signal: options.timeout ? AbortSignal.timeout(options.timeout) : undefined,
};
}
async function parseXml(response: Response) {
const text = await response.text();
try {
const result = await xml2js.parseStringPromise(text);
return result;
} catch (error: any) {
throw new Error(`XML parse error: ${error?.message}`);
}
}