-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapiCore.ts
More file actions
76 lines (70 loc) · 2.09 KB
/
apiCore.ts
File metadata and controls
76 lines (70 loc) · 2.09 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { logger } from "@/logger.js";
import { request, Dispatcher, FormData } from "undici";
import { InputSource, PageOptions, LocalInputSource } from "@/input/index.js";
export const TIMEOUT_SECS_DEFAULT: number = 120;
export interface RequestOptions {
hostname?: string;
path?: string;
method: any;
timeoutSecs: number;
headers: any;
body?: FormData | string;
}
export interface BaseHttpResponse {
messageObj: any;
data: { [key: string]: any };
}
/**
* Cuts a document's pages according to the given options.
* @param inputDoc input document.
* @param pageOptions page cutting options.
*/
export async function cutDocPages(inputDoc: InputSource, pageOptions: PageOptions) {
if (inputDoc instanceof LocalInputSource && inputDoc.isPdf()) {
await inputDoc.applyPageOptions(pageOptions);
}
}
/**
* Reads a response from the API and processes it.
* @param dispatcher custom dispatcher to use for the request.
* @param options options related to the request itself.
* @param url override the URL of the request.
* @returns the processed request.
*/
export async function sendRequestAndReadResponse(
dispatcher: Dispatcher,
options: RequestOptions,
url?: string,
): Promise<BaseHttpResponse> {
url ??= `https://${options.hostname}${options.path}`;
const response = await request(
url,
{
method: options.method,
headers: options.headers,
headersTimeout: options.timeoutSecs * 1000,
body: options.body,
dispatcher: dispatcher,
}
);
logger.debug("Parsing the response ...");
let responseBody: string = await response.body.text();
// handle empty responses from server, for example, in the case of redirects
if (!responseBody) {
responseBody = "{}";
}
try {
const parsedResponse = JSON.parse(responseBody);
logger.debug("JSON parsed successfully, returning plain object.");
return {
messageObj: response,
data: parsedResponse,
};
} catch {
logger.error("Could not parse the return as JSON.");
return {
messageObj: response,
data: { reconstructedResponse: responseBody },
};
}
}