UNPKG

axios-inference-polling

Version:

A package for polling the inference status until it is completed.

77 lines (76 loc) 3.37 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Inference = void 0; const axios_1 = require("axios"); const sleep = (timeInMs) => new Promise((resolve) => setTimeout(resolve, timeInMs)); class Inference { constructor() { this.axios = new axios_1.Axios(); this.subscribers = []; } subscribeToEvents(handler) { if (typeof handler !== "function") throw new Error("Not a valid subscriber function"); this.subscribers = [...this.subscribers, handler]; } unsubscribeToEvents(handler) { if (typeof handler !== "function") throw new Error("Not a valid subscriber function"); this.subscribers = this.subscribers.filter((sub) => sub !== handler); } emitEvent(event, type) { this.subscribers.forEach((sub) => sub(event, type)); } createInferenceRequest(_a) { return __awaiter(this, arguments, void 0, function* ({ create_prediction_url, payload, config, onError, }) { try { const { data } = yield this.axios.post(create_prediction_url, payload, config); this.emitEvent(data, "CREATE_PREDICTION"); return data; } catch (error) { if (onError) onError(error); throw new Error(`Error while creating prediction, error: ${JSON.stringify(error)}`); } }); } pollInferenceRequest(_a) { return __awaiter(this, arguments, void 0, function* ({ create_prediction_url, prediction_status_url, payload, config, onError, }) { let prediction = yield this.createInferenceRequest({ create_prediction_url, payload, config, onError, }); while (prediction && prediction.status !== "succeeded" && prediction.status !== "failed" && prediction.status !== "canceled") { yield sleep(2000); try { const { data } = yield this.axios.get(`/${prediction_status_url}/${prediction.id}`); prediction = data; } catch (error) { if (onError) onError(error); throw new Error(`Error while getting prediction status, error: ${JSON.stringify(error)}`); } this.emitEvent(prediction, "UPDATE_PREDICTION"); } this.emitEvent(prediction, "UPDATE_PREDICTION"); return prediction; }); } } exports.Inference = Inference;