poe-api-manager
Version:
poe.ninja and poe.watch API
75 lines (74 loc) • 3.5 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const mergeData_1 = __importDefault(require("./merge/mergeData"));
const urlGenerator_1 = __importDefault(require("../func/urlGenerator"));
const ApiError_1 = __importDefault(require("../../../errors/ApiError"));
/**
* Fetches data from a specified API endpoint, merges relevant data, and returns the result.
* @param league The game league for which to fetch data.
* @param type The type of data to fetch. (e.g. "Currency", "Fragment")
* @param typeName The name of the type of data to fetch. (e.g. "CurrencyOverview", "ItemOverview")
* @returns A promise that resolves to an array of merged objects containing both line and currency details.
* @throws Throws an error if there's an issue with the API response or data fetching process.
*/
async function fetchData(league, typeName, type) {
try {
// Generate the URL for the specified league, type name, and type
const url = (0, urlGenerator_1.default)(league, typeName, type);
//axios.get(url) is a promise
const response = await axios_1.default.get(url, {
headers: {
"Accept-Encoding": "identity",
},
});
//typwName is either currencyoverview or itemoverview
if (typeName == "currencyoverview") {
//if the response has data and lines and currencyDetails
if (response.data &&
response.data.lines &&
response.data.currencyDetails) {
const lines = response.data.lines;
const currencyDetails = response.data.currencyDetails;
//the join data is the currencyDetails
return (0, mergeData_1.default)(lines, currencyDetails);
}
else {
throw new ApiError_1.default(`Invalid response format from POE Ninja API CurrencyView Type:${type}`, 400, { league, typeName, type });
}
}
else if (typeName == "itemoverview") {
//if the response has data and lines
if (response.data && response.data.lines) {
return response.data.lines;
}
else {
throw new ApiError_1.default(`Invalid response format from POE Ninja API ItemView Type:${type}`, 400, { league, typeName, type });
}
}
else {
throw new ApiError_1.default(`Invalid type: ${type}`, 400, {
league,
typeName,
type,
});
}
}
catch (error) {
// If it's already an ApiError, pass it through
if (error instanceof ApiError_1.default) {
throw error;
}
// Handle axios errors with more context
if (axios_1.default.isAxiosError(error)) {
const statusCode = error.response?.status || 500;
throw new ApiError_1.default(`Error fetching data: ${error.message} TypeName:${typeName} and Type:${type}`, statusCode, { url: error.config?.url, league, typeName, type });
}
// General error case
throw new ApiError_1.default(`Error fetching data: ${error.message} TypeName:${typeName} and Type:${type}`, 500, { league, typeName, type });
}
}
exports.default = fetchData;