mindee
Version:
Mindee Client Library for Node.js
78 lines (77 loc) • 2.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseEndpoint = void 0;
const logger_1 = require("../logger");
const https_1 = require("https");
const input_1 = require("../input");
/**
* Base endpoint for the Mindee API.
*/
class BaseEndpoint {
constructor(settings, urlRoot) {
this.settings = settings;
this.urlRoot = urlRoot;
}
/**
* Cuts a document's pages according to the given options.
* @param inputDoc input document.
* @param pageOptions page cutting options.
*/
static async cutDocPages(inputDoc, pageOptions) {
if (inputDoc instanceof input_1.LocalInputSource && inputDoc.isPdf()) {
await inputDoc.applyPageOptions(pageOptions);
}
}
/**
* Reads a response from the API and processes it.
* @param options options related to the request itself.
* @param resolve the resolved response
* @param reject promise rejection reason.
* @returns the processed request.
*/
static readResponse(options, resolve, reject) {
logger_1.logger.debug(`${options.method}: https://${options.hostname}${options.path}`);
const req = (0, https_1.request)(options, function (res) {
// when the encoding is set, data chunks will be strings
res.setEncoding("utf-8");
let responseBody = "";
res.on("data", function (chunk) {
logger_1.logger.debug("Receiving data ...");
responseBody += chunk;
});
res.on("end", function () {
logger_1.logger.debug("Parsing the response ...");
// handle empty responses from server, for example in the case of redirects
if (!responseBody) {
responseBody = "{}";
}
try {
const parsedResponse = JSON.parse(responseBody);
try {
resolve({
messageObj: res,
data: parsedResponse,
});
}
catch (error) {
logger_1.logger.error("Could not construct the return object.");
reject(error);
}
}
catch {
logger_1.logger.error("Could not parse the return as JSON.");
logger_1.logger.debug(responseBody);
resolve({
messageObj: res,
data: { reconstructedResponse: responseBody },
});
}
});
});
req.on("error", (err) => {
reject(err);
});
return req;
}
}
exports.BaseEndpoint = BaseEndpoint;