UNPKG

jspteroapi

Version:

A pterodactyl v1 api using undici

58 lines (57 loc) 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Request = void 0; const undici_1 = require("undici"); const Error_1 = require("./Error"); class Request { host; key; errorHandler; constructor(host, key, errorHandler) { this.host = host; this.key = key; this.errorHandler = errorHandler; } /** * @param requestType - The type of request to use e. g. GET, POST * @param data - Data to send * @param dataObj - Data object to return / Text to give on success * @param endpoint - Endpoint for server to call * @param text - Boolean if we want to return text of the response */ async request(requestType, data, dataObj, endpoint, text = false // eslint-disable-next-line @typescript-eslint/no-explicit-any ) { const URL = this.host + endpoint; const options = { method: requestType, headers: { 'responseEncoding': 'utf8', 'Authorization': 'Bearer ' + this.key, 'Content-Type': `${!endpoint.includes('files/write') ? 'application/json' : ''}`, 'Accept': 'application/json' } }; if (data && endpoint.includes('files/write')) options.body = data; if (data && !endpoint.includes('files/write')) options.body = JSON.stringify(data); const rawData = await (0, undici_1.fetch)(URL, options); if (!rawData.ok) return this.errorHandler(new Error_1.JSPteroAPIError(rawData, (await rawData.json()), data, requestType)); if (rawData.status === 204 || rawData.status === 202) return dataObj; if (text) return await rawData.text(); // eslint-disable-next-line @typescript-eslint/no-explicit-any let res = (await rawData.json()); if (!dataObj) return res; const objArr = dataObj.split('.'); objArr.forEach((obj) => { res = res[obj]; }); return res; } } exports.Request = Request;