geneea-nlp-client
Version:
The TypeScript Client for Geneea Interpretor G3 API.
80 lines (79 loc) • 3.44 kB
JavaScript
;
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.Client = void 0;
const http_1 = require("http");
const axios_1 = require("axios");
const __1 = require("..");
/**
* A client for the Geneea NLP REST (General API V3).
*/
class Client {
constructor(url, userKey, timeout) {
this.url = url;
this.userKey = userKey;
this.timeout = timeout;
this.httpAgent = new http_1.Agent({ keepAlive: true });
}
/**
* Call Geneea G3 API.
* @param request A Request instance (data to analyze and parameters).
* @returns A promise that resolves to the result as an Analysis object.
*/
analyze(request) {
return __awaiter(this, void 0, void 0, function* () {
const options = {
method: "post",
headers: {
Accept: "application/json; charset=UTF-8",
Authorization: `user_key ${this.userKey}`,
"Content-Type": "application/json; charset=UTF-8",
},
timeout: this.timeout,
responseType: "json",
httpAgent: this.httpAgent,
};
try {
const response = yield axios_1.default.post(this.url, request.toJson(), options);
return (0, __1.readFromJson)(response.data);
}
catch (error) {
if (error.response) {
throw new Error(`API call failure with HTTP code ${error.response.status}
${JSON.stringify(error.response.data)}`);
}
else {
throw error;
}
}
});
}
/**
* Create Geneea G3 Client.
*
* @param url URL of the Interpretor API to use.
* @param userKey API user key; if not specified, loaded from `GENEEA_API_KEY` environment variable.
* @param timeout A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected. [DEFAULT_TIMEOUT_SEC] if not set.
* @returns A G3 client.
*/
static create(url = this.DEFAULT_URL, userKey = "ANONYMOUS", timeout = this.DEFAULT_TIMEOUT_MILLISEC) {
var _a;
const key = (_a = process.env.GENEEA_API_KEY) !== null && _a !== void 0 ? _a : userKey;
if (!key) {
console.warn("[Warning] No user key specified: neither as a parameter nor as a GENEEA_API_KEY environment variable");
}
return new Client(url, key, timeout);
}
}
exports.Client = Client;
/** The default address of the Geneea NLP G3 API. */
Client.DEFAULT_URL = "https://api.geneea.com/v3/analysis";
Client.DEFAULT_TIMEOUT_MILLISEC = 600000;