UNPKG

@traversets/code-extractor

Version:

The TypeScript Code Extractor and Analyzer can be handy for RAG (Retrieval-Augmented Generation) systems for codebases. It provides a detailed and structured representation of the codebase that can be converted into embeddings, enabling more effective adv

190 lines 8.04 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpClient = void 0; const https = __importStar(require("https")); const logger_service_1 = require("../logger/logger-service"); const constants_1 = require("../core/constants"); /** * A custom HTTP client implementation that provides a set of methods for sending HTTP requests. * This client supports GET, POST, PUT, and DELETE requests, and allows for optional request options and payload. * It also handles JSON parsing and error logging. */ class HttpClient { logger; constructor() { this.logger = new logger_service_1.ApplicationLogger(); } /* Retrieves a resource asynchronously using the GET method. @param options - Optional request options @returns A Promise that resolves to the response data **/ async get(payload, options) { return this.sendRequest("GET", options, payload); } /* Sends a request with a payload using the POST method. * @param payload - The request payload * @param options - Optional request options * @returns A Promise that resolves to the response data **/ async post(payload, options) { return this.sendRequest("POST", options, payload); } /* Updates a resource asynchronously using the PUT method. @param payload - The request payload * @param options - Optional request options @returns A Promise that resolves to the response data **/ async put(payload, options) { return this.sendRequest("PUT", options, payload); } /* Deletes a resource asynchronously using the DELETE method. @param options - Optional request options @returns A Promise that resolves to the response data **/ async delete(options) { return this.sendRequest("DELETE", options); } /* Sends a request with a method, options, and optional payload. @param method - The request method (GET, POST, PUT, DELETE, etc.) @param options - Optional request options @param payload - The request payload (optional) @returns A Promise that resolves to the response data */ async sendRequest(method, options, payload, jwtToken) { const defaultHeader = this.generateRequestHeader(jwtToken); options.header = { ...options.header, ...defaultHeader }; return new Promise((resolve, reject) => { const requestOptions = { method, ...options, }; const req = https.request(requestOptions, (res) => { let data = ""; res.on("data", (chunk) => { data += chunk; }); res.on("end", () => { try { if (res.statusCode && res.statusCode < 500) { try { // TODO need to look into response type especially for getSchemas console.log(data); if (Array.isArray(data)) { console.log({ array: data }); data = JSON.stringify(data); } if (typeof data !== "string") { console.log({ string: data }); data = JSON.stringify(data); } const parsedData = JSON.parse(data); resolve(parsedData); } catch (error) { console.log(error); reject(new Error(`Failed to parse response data: ${error.message}`)); throw error; } } else { reject(new Error(`Request failed with status code ${res.statusCode}`)); } } catch (error) { this.logger.error("An error occurred during the API request.", JSON.stringify(error), error); throw error; } }); }); req.on("error", (error) => { this.logger.error("An error occurred during the API request.", JSON.stringify(error), error); reject(error); throw error; }); req.write(payload); req.end(); }); } /** * Returns an object with the required headers for API requests. * The authorization header uses a JWT token stored in local storage, which has a lifespan of 4 days (4 * 24 * 60 * 60). * @returns An object with the "Authorization" and "Content-Type" headers */ generateRequestHeader(jwtToken) { return { [constants_1.RequestHeader.AUTHORIZATION]: `Bearer ${jwtToken}`, [constants_1.RequestHeader.CONTENT_TYPE]: "application/json", [constants_1.RequestHeader.CONNECTION]: "keep-alive", [constants_1.RequestHeader.ACCEPT]: "*/*", }; } generateRequestOptions(method, path, baseUrl, jwtToken) { const headers = this.generateRequestHeader(jwtToken); const options = { hostname: baseUrl, path, method: method.toUpperCase(), headers, }; return options; } /** * Initiates a request to the server with the provided data and request type. * @param url - The URL of the request. * @param data - The data to be sent with the request. * @param requestType - The type of request (either "post" or "get"). * @param requestToken - An optional request token for authentication. * @returns A promise that resolves to the response from the server. */ async inititateRequest(method, path, baseUrl, data, jwtToken) { try { const requestOptions = this.generateRequestOptions(method, path, baseUrl, jwtToken); let response; switch (method) { case constants_1.HTTP_VERBS.GET: response = await this.get(Buffer.from(JSON.stringify({})), requestOptions); case constants_1.HTTP_VERBS.POST: response = await this.post(Buffer.from(JSON.stringify(data)), requestOptions); break; default: break; } if (!response) { throw new Error("API call failed"); } return response; } catch (error) { this.logger.error("An error occurred during the API request.", JSON.stringify(error), error); throw error; } } } exports.HttpClient = HttpClient; //# sourceMappingURL=http-service.js.map