parea-ai
Version:
Client SDK library to connect to Parea AI.
138 lines (137 loc) • 4.53 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPClient = void 0;
const axios_1 = __importDefault(require("axios"));
const axios_retry_1 = __importDefault(require("axios-retry"));
/**
* A singleton class for making HTTP requests with configurable options and mock mode.
*/
class HTTPClient {
constructor() {
this.apiKey = null;
this.mockMode = false;
this.defaultMockResponse = {
data: { message: 'mock' },
status: 200,
statusText: 'OK',
config: {},
headers: {},
};
this.client = axios_1.default.create({
baseURL: this.baseURL,
timeout: 60 * 3.0 * 1000,
});
// Apply retry mechanism with axios-retry
(0, axios_retry_1.default)(this.client, { retries: 2, retryDelay: (...arg) => axios_retry_1.default.exponentialDelay(...arg, 500) });
this.client.interceptors.request.use(this.requestInterceptor);
this.client.interceptors.response.use(this.responseInterceptor, this.errorInterceptor);
}
/**
* Gets the singleton instance of the HTTPClient.
* @returns The HTTPClient instance.
*/
static getInstance() {
if (!HTTPClient.instance) {
HTTPClient.instance = new HTTPClient();
}
return HTTPClient.instance;
}
/**
* Sets a custom mock response message.
* @param mockMessage - The message to be used in the mock response.
*/
setMockHandler(mockMessage) {
this.defaultMockResponse = {
...this.defaultMockResponse,
data: { message: mockMessage },
};
}
/**
* Enables or disables mock mode.
* @param enable - Boolean flag to enable or disable mock mode.
*/
enableMockMode(enable) {
this.mockMode = enable;
}
/**
* Sets the API key for authentication.
* @param apiKey - The API key to be used for requests.
*/
setApiKey(apiKey) {
this.apiKey = apiKey;
}
/**
* Sets the base URL for all requests.
* @param baseURL - The base URL to be used.
*/
setBaseURL(baseURL) {
this.baseURL = baseURL;
this.client.defaults.baseURL = baseURL;
}
/**
* Sends an HTTP request based on the provided configuration.
* @param config - The request configuration.
* @returns A promise that resolves to the axios response.
* @throws Will throw an error if the request fails.
*/
async request(config) {
if (!this.apiKey) {
console.log(`No API key`);
return Promise.reject();
}
if (this.mockMode) {
return Promise.resolve(this.defaultMockResponse);
}
else {
const headers = {
'x-api-key': this.apiKey || config.apiKey || '',
'x-sdk-language': 'typescript',
};
try {
return await this.client.request({
method: config.method,
url: config.endpoint,
data: config.data,
params: config.params,
headers,
});
}
catch (error) {
console.error(`Request to ${config.endpoint} failed with error ${error}`);
throw error;
}
}
}
/**
* Intercepts and processes the request before it is sent.
* @param config - The request configuration.
* @returns The processed request configuration.
*/
requestInterceptor(config) {
return config;
}
/**
* Intercepts and processes the response before it is handled.
* @param response - The axios response object.
* @returns The processed response.
*/
responseInterceptor(response) {
return response;
}
/**
* Intercepts and processes errors that occur during the request.
* @param error - The axios error object.
* @returns A rejected promise with the error.
* @throws Will throw a custom error if the server is down or unavailable.
*/
errorInterceptor(error) {
if (error?.code === 'ECONNREFUSED') {
throw new Error('Server is down or unavailable.');
}
return Promise.reject(error);
}
}
exports.HTTPClient = HTTPClient;