UNPKG

ade-planning-api

Version:

An unofficial API wrapper for ADE Planning from Adesoft

74 lines (73 loc) 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ADEFetcher = void 0; const xml2js_1 = require("xml2js"); class ADEFetcher { apiUrl; sessionToken = null; constructor(baseUrl) { this.apiUrl = `${baseUrl}/jsp/webapi`; } /** * Initializes a new session with the API. * @param credentials The credentials to use for authentication. * @returns A promise that resolves when the session is initialized. */ async initializeSession(credentials) { const queryString = new URLSearchParams({ login: credentials.username, password: credentials.password, function: "connect", }).toString(); const response = await fetch(`${this.apiUrl}?${queryString}`, { method: "GET", headers: { "Content-Type": "application/xml" }, }); if (!response.ok) { throw new Error("Failed to initialize session."); } const xmlData = await response.text(); const parsedData = await (0, xml2js_1.parseStringPromise)(xmlData); this.sessionToken = parsedData?.session?.$.id; if (!this.sessionToken) { throw new Error("Session ID not found in the response."); } } /** * Terminates the current session with the API. * @returns A promise that resolves when the session is terminated. */ async terminateSession() { if (!this.sessionToken) { throw new Error("Session token not found."); } const queryString = new URLSearchParams({ session: this.sessionToken, function: "disconnect", }).toString(); await fetch(`${this.apiUrl}?${queryString}`, { method: "GET", headers: { "Content-Type": "application/xml" }, }); this.sessionToken = null; } /** * Fetches data from the API. * @param params The parameters to include in the request. * @returns A promise that resolves with the fetched data. */ async get(params) { if (!this.sessionToken) { throw new Error("Session token not found."); } const queryString = (new URLSearchParams({ ...(params || {}), sessionId: this.sessionToken })).toString(); // Add params and session token to the query string const response = await fetch(`${this.apiUrl}?${queryString}`, { method: "GET", headers: { "Content-Type": "application/xml" }, }); const xmlData = await response.text(); const parsedData = await (0, xml2js_1.parseStringPromise)(xmlData); return parsedData; } } exports.ADEFetcher = ADEFetcher;