@maximai/maxim-js
Version:
Maxim AI JS SDK. Visit https://getmaxim.ai for more info.
86 lines • 3.39 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaximAPI = void 0;
const http_1 = __importDefault(require("http"));
const https_1 = __importDefault(require("https"));
class MaximAPI {
constructor(baseUrl, apiKey) {
this.httpAgent = new http_1.default.Agent({ keepAlive: false });
this.httpsAgent = new https_1.default.Agent({ keepAlive: false });
this.baseUrl = baseUrl;
this.apiKey = apiKey;
}
fetch(relativeUrl, { method, headers, body, } = {}) {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(this.baseUrl + relativeUrl);
const isLocalhost = parsedUrl.hostname === "localhost";
const options = {
hostname: parsedUrl.hostname,
port: isLocalhost ? parsedUrl.port || 3000 : 443,
path: parsedUrl.pathname + parsedUrl.search,
method: method !== null && method !== void 0 ? method : "GET",
headers: {
"x-maxim-api-key": this.apiKey,
...headers,
},
agent: isLocalhost ? this.httpAgent : this.httpsAgent,
};
const requestModule = isLocalhost ? http_1.default : https_1.default;
const makeRequest = (retryCount = 0) => {
const req = requestModule.request(options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
resolve(response);
}
catch (error) {
if (retryCount < 3) {
setTimeout(() => makeRequest(retryCount + 1), 30);
}
else {
reject(error);
}
}
});
});
req.on("timeout", () => {
req.destroy();
if (retryCount < 3) {
setTimeout(() => makeRequest(retryCount + 1), 30);
}
else {
reject(new Error("Request timed out"));
}
});
req.on("error", (error) => {
console.error("Error while connecting to Maxim Server", error);
req.destroy();
if (retryCount < 3) {
setTimeout(() => makeRequest(retryCount + 1), 30);
}
else {
reject(error);
}
});
if (body) {
req.write(body);
}
req.end();
};
makeRequest();
});
}
destroyAgents() {
this.httpAgent.destroy();
this.httpsAgent.destroy();
}
}
exports.MaximAPI = MaximAPI;
//# sourceMappingURL=maxim.js.map