@azure/ai-text-analytics
Version:
An isomorphic client library for the Azure Text Analytics service.
236 lines • 10.2 kB
JavaScript
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __asyncDelegator, __asyncGenerator, __asyncValues, __await } from "tslib";
import { makeHealthcareEntitiesResult, makeHealthcareEntitiesErrorResult } from "../../analyzeHealthcareEntitiesResult";
import { addStrEncodingParam, getOperationId, handleInvalidDocumentBatch, nextLinkToTopAndSkip } from "../../util";
import { AnalysisPollOperation } from "../poller";
import { processAndCombineSuccessfulAndErroneousDocuments } from "../../textAnalyticsResult";
import { SpanStatusCode } from "@azure/core-tracing";
import { createSpan } from "../../tracing";
/**
* @internal
*/
function getMetaInfoFromResponse(response) {
return {
createdOn: response.createdDateTime,
lastModifiedOn: response.lastUpdateDateTime,
expiresOn: response.expirationDateTime,
status: response.status
};
}
/**
* Class that represents a poller that waits for the healthcare results.
* @internal
*/
export class BeginAnalyzeHealthcarePollerOperation extends AnalysisPollOperation {
constructor(state,
// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters
client, documents, options = {}) {
super(state);
this.state = state;
this.client = client;
this.documents = documents;
this.options = options;
}
/**
* should be called only after all the status of the healthcare operations became
* "succeeded" and it returns an iterator for the results and provides a
* byPage method to return the results paged.
*/
listHealthcareEntitiesByPage(operationId, options = {}) {
const iter = this._listHealthcareEntities(operationId, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: (settings) => {
const pageOptions = Object.assign(Object.assign({}, options), { top: settings === null || settings === void 0 ? void 0 : settings.maxPageSize });
return this._listHealthcareEntitiesPaged(operationId, pageOptions);
}
};
}
/**
* returns an iterator to the results of a healthcare operation.
*/
_listHealthcareEntities(operationId, options) {
return __asyncGenerator(this, arguments, function* _listHealthcareEntities_1() {
var e_1, _a;
try {
for (var _b = __asyncValues(this._listHealthcareEntitiesPaged(operationId, options)), _c; _c = yield __await(_b.next()), !_c.done;) {
const page = _c.value;
yield __await(yield* __asyncDelegator(__asyncValues(page)));
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));
}
finally { if (e_1) throw e_1.error; }
}
});
}
/**
* returns an iterator to arrays of the results of a healthcare operation.
*/
_listHealthcareEntitiesPaged(operationId, options) {
return __asyncGenerator(this, arguments, function* _listHealthcareEntitiesPaged_1() {
let response = yield __await(this._listHealthcareEntitiesSinglePage(operationId, options));
yield yield __await(response.result);
while (response.skip) {
const optionsWithContinuation = Object.assign(Object.assign({}, options), { top: response.top, skip: response.skip });
response = yield __await(this._listHealthcareEntitiesSinglePage(operationId, optionsWithContinuation));
yield yield __await(response.result);
}
});
}
/**
* returns an iterator to arrays of the sorted results of a healthcare operation.
*/
async _listHealthcareEntitiesSinglePage(operationId, options) {
const { span, updatedOptions: finalOptions } = createSpan("TextAnalyticsClient-_listHealthcareEntitiesSinglePage", options || {});
try {
const response = await this.client.healthStatus(operationId, finalOptions);
if (response.results) {
const result = processAndCombineSuccessfulAndErroneousDocuments(this.documents, response.results, makeHealthcareEntitiesResult, makeHealthcareEntitiesErrorResult);
return response.nextLink
? Object.assign({ result }, nextLinkToTopAndSkip(response.nextLink)) : { result };
}
else {
throw new Error("Healthcare action has succeeded but the there are no results!");
}
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* returns whether the healthcare operation is done and if so returns also
* statistics and the model version used.
*/
async getHealthStatus(operationId, options) {
var _a;
const { span, updatedOptions: finalOptions } = createSpan("TextAnalyticsClient-getHealthStatus", options || {});
try {
const response = await this.client.healthStatus(operationId, finalOptions);
switch (response.status) {
case "notStarted":
case "running":
break;
case "failed": {
const errors = (_a = response.errors) === null || _a === void 0 ? void 0 : _a.map((e) => ` code ${e.code}, message: '${e.message}'`).join("\n");
const message = `Healthcare analysis failed. Error(s): ${errors || ""}`;
throw new Error(message);
}
default: {
if (response.results) {
return {
done: true,
statistics: response.results.statistics,
modelVersion: response.results.modelVersion,
operationMetdata: getMetaInfoFromResponse(response)
};
}
else {
throw new Error("Healthcare action has finished but the there are no results!");
}
}
}
return { done: false, operationMetdata: getMetaInfoFromResponse(response) };
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
async beginAnalyzeHealthcare(documents, options) {
const { span, updatedOptions: finalOptions } = createSpan("TextAnalyticsClient-beginAnalyzeHealthcare", addStrEncodingParam(options || {}));
try {
return await this.client.health({ documents: documents }, finalOptions);
}
catch (e) {
const exception = handleInvalidDocumentBatch(e);
span.setStatus({
code: SpanStatusCode.ERROR,
message: exception.message
});
throw exception;
}
finally {
span.end();
}
}
async update(options = {}) {
const state = this.state;
const updatedAbortSignal = options.abortSignal;
if (!state.isStarted) {
state.isStarted = true;
const response = await this.beginAnalyzeHealthcare(this.documents, {
requestOptions: this.options.requestOptions,
tracingOptions: this.options.tracingOptions,
abortSignal: updatedAbortSignal ? updatedAbortSignal : options.abortSignal,
modelVersion: this.options.modelVersion,
stringIndexType: this.options.stringIndexType,
loggingOptOut: this.options.disableServiceLogs
});
if (!response.operationLocation) {
throw new Error("Expects a valid 'operationLocation' to retrieve health results but did not find any");
}
state.operationId = getOperationId(response.operationLocation);
}
const operationStatus = await this.getHealthStatus(state.operationId, {
abortSignal: updatedAbortSignal ? updatedAbortSignal : options.abortSignal,
includeStatistics: this.options.includeStatistics,
tracingOptions: this.options.tracingOptions,
onResponse: this.options.onResponse,
serializerOptions: this.options.serializerOptions
});
state.createdOn = operationStatus.operationMetdata.createdOn;
state.expiresOn = operationStatus.operationMetdata.expiresOn;
state.lastModifiedOn = operationStatus.operationMetdata.lastModifiedOn;
state.status = operationStatus.operationMetdata.status;
if (!state.isCompleted && operationStatus.done) {
const pagedIterator = this.listHealthcareEntitiesByPage(state.operationId, {
abortSignal: this.options.abortSignal,
tracingOptions: this.options.tracingOptions
});
state.result = Object.assign(pagedIterator, {
statistics: operationStatus.statistics,
modelVersion: operationStatus.modelVersion
});
state.isCompleted = true;
}
if (typeof options.fireProgress === "function") {
options.fireProgress(state);
}
return this;
}
async cancel() {
const state = this.state;
if (state.operationId) {
await this.client.cancelHealthJob(state.operationId, {
abortSignal: this.options.abortSignal,
tracingOptions: this.options.tracingOptions
});
}
state.isCancelled = true;
return this;
}
}
//# sourceMappingURL=operation.js.map