-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhttpRequest.ts
More file actions
62 lines (51 loc) · 2.3 KB
/
httpRequest.ts
File metadata and controls
62 lines (51 loc) · 2.3 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { HttpErrorResponse, UnauthorizedError } from './errors';
export function getNextLinkFromHeaders(headers: Headers, baseUrl: vscode.Uri): vscode.Uri | undefined {
const linkHeader = headers.get('link');
if (!linkHeader) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = linkHeader.match(/<(.*)>; rel="next"/i);
if (!match) {
return undefined;
}
const headerUri = vscode.Uri.parse(match[1]);
const nextLinkUri = baseUrl.with({ path: headerUri.path, query: headerUri.query });
return nextLinkUri;
}
export type HeadersLike = Headers;
export type RequestLike = RequestInit & {
headers: Record<string, string>;
};
export interface ResponseLike<T> extends Response {
headers: HeadersLike;
status: number;
statusText: string;
succeeded: boolean;
json: () => Promise<T>;
}
export async function httpRequest<T>(url: string, request: RequestLike, throwOnFailure: boolean = true): Promise<ResponseLike<T>> {
if (!!request.body && request.duplex === undefined) {
// node-fetch requires the "duplex" option to be set to "half" in order to send a body
request.duplex = 'half';
}
const response: Response = await fetch(url, request);
if (throwOnFailure && response.status === 401) {
throw new UnauthorizedError(vscode.l10n.t('Request to \'{0}\' failed with response 401: Unauthorized', url));
} else if (throwOnFailure && !response.ok) {
throw new HttpErrorResponse(url, response.status, response.statusText);
}
return {
...response,
headers: response.headers, // These are getters so we need to call them to get the values
status: response.status,
statusText: response.statusText,
succeeded: response.ok,
json: response.json.bind(response) as () => Promise<T>,
};
}