UNPKG

mindee

Version:

Mindee Client Library for Node.js

153 lines (152 loc) 7.06 kB
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _MindeeApiV2_instances, _MindeeApiV2_processResponse; import { ApiSettings } from "./apiSettings.js"; import { ErrorResponse, JobResponse, } from "../../v2/parsing/index.js"; import { sendRequestAndReadResponse } from "../../http/apiCore.js"; import { LocalInputSource } from "../../input/index.js"; import { MindeeDeserializationError, MindeeError } from "../../errors/index.js"; import { MindeeHttpErrorV2 } from "./errors.js"; import { logger } from "../../logger.js"; import { SearchResponse } from "../../v2/parsing/search/index.js"; /** * Mindee V2 API handler. */ export class MindeeApiV2 { constructor(dispatcher, apiKey) { _MindeeApiV2_instances.add(this); this.settings = new ApiSettings({ dispatcher: dispatcher, apiKey: apiKey }); } /** * Search for models available to the account. * @param name Optional name filter. * @param modelType Optional model type filter. * @returns a `Promise` containing the search response. */ async reqGetSearchModel(name, modelType) { const queryParams = {}; if (name) queryParams["name"] = name; if (modelType) queryParams["model_type"] = modelType; const options = { method: "GET", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: "/v2/search/models", queryParams: queryParams, timeoutSecs: this.settings.timeoutSecs, }; const response = await sendRequestAndReadResponse(this.settings.dispatcher, options); return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, response, SearchResponse); } /** * Sends a document to the inference queue. * @param product Product to enqueue. * @param inputSource Local or remote file as an input. * @param params {ExtractionParameters} parameters relating to the enqueueing options. */ async reqPostProductEnqueue(product, inputSource, params) { const form = params.getFormData(); if (inputSource instanceof LocalInputSource) { form.set("file", new Blob([inputSource.fileObject]), inputSource.filename); } else { form.set("url", inputSource.url); } const path = `/v2/products/${product.slug}/enqueue`; const options = { method: "POST", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: path, body: form, timeoutSecs: this.settings.timeoutSecs, }; const result = await sendRequestAndReadResponse(this.settings.dispatcher, options); if (result.data.error !== undefined) { throw new MindeeHttpErrorV2(result.data.error); } return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, result, JobResponse); } /** * Get the specified Job by its ID. * Throws an error if the server's response contains an error. * @param jobId The Job ID as returned by the enqueue request. * @returns a `Promise` containing the job response. */ async reqGetJobById(jobId) { return this.reqGetJobByUrl(`https://${this.settings.hostname}/v2/jobs/${jobId}`); } /** * Get the specified Job from a polling URL. * Throws an error if the server's response contains an error. * @param pollingUrl The polling URL as returned by a Job's pollingUrl property. * @returns a `Promise` containing the job response. */ async reqGetJobByUrl(pollingUrl) { if (!pollingUrl.startsWith("https://")) { throw new MindeeError(`Invalid URL: ${pollingUrl}`); } const options = { method: "GET", headers: this.settings.baseHeaders, timeoutSecs: this.settings.timeoutSecs, }; const response = await sendRequestAndReadResponse(this.settings.dispatcher, options, pollingUrl); return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, response, JobResponse); } /** * Get the result of a queued document from the API. * Throws an error if the server's response contains an error. * @param product * @param inferenceId The inference ID for the result. * @returns a `Promise` containing the parsed result. */ async reqGetProductResultById(product, inferenceId) { return this.reqGetProductResultByUrl(product, `https://${this.settings.hostname}/v2/products/${product.slug}/results/${inferenceId}`); } /** * Get the result of a queued document from the API. * Throws an error if the server's response contains an error. * @param product * @param url The URL as returned by a Job's resultUrl property. * @returns a `Promise` containing the parsed result. */ async reqGetProductResultByUrl(product, url) { const options = { method: "GET", headers: this.settings.baseHeaders, timeoutSecs: this.settings.timeoutSecs, }; if (!url.startsWith("https://")) { throw new MindeeError(`Invalid URL: ${url}`); } const response = await sendRequestAndReadResponse(this.settings.dispatcher, options, url); return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, response, product.responseClass); } } _MindeeApiV2_instances = new WeakSet(), _MindeeApiV2_processResponse = function _MindeeApiV2_processResponse(result, responseClass) { if (result.messageObj?.statusCode && (result.messageObj?.statusCode > 399 || result.messageObj?.statusCode < 200)) { if (result.data?.status !== null) { throw new MindeeHttpErrorV2(new ErrorResponse(result.data)); } throw new MindeeHttpErrorV2(new ErrorResponse({ status: result.messageObj?.statusCode ?? -1, title: "Unknown Error", detail: result.data?.detail ?? "The server returned an Unknown error.", code: `${result.messageObj?.statusCode ?? -1}-000`, })); } try { return new responseClass(result.data); } catch (e) { logger.error(`Raised '${e}' Couldn't deserialize response object:\n${JSON.stringify(result.data)}`); throw new MindeeDeserializationError("Couldn't deserialize response object."); } };