enka-network-api
Version:
Enka-network API wrapper for Genshin Impact.
51 lines (50 loc) • 2.12 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultFetchStringOptions = void 0;
exports.fetchString = fetchString;
const fs_1 = __importDefault(require("fs"));
const axios_1 = __importDefault(require("axios"));
const config_file_js_1 = require("config_file.js");
;
exports.defaultFetchStringOptions = {
enableTimeout: false,
allowLocalFile: false,
};
async function fetchString(options) {
const { url, enka, enableTimeout, allowLocalFile } = (0, config_file_js_1.bindOptions)(exports.defaultFetchStringOptions, options);
if (allowLocalFile && url.startsWith("file://")) {
const path = url.slice("file://".length);
if (!fs_1.default.existsSync(path) || !fs_1.default.statSync(path).isFile())
throw new Error(`Failed to fetch string from ${url}. File does not exist or is not a file.`);
return fs_1.default.readFileSync(path, "utf-8");
}
const headers = { "User-Agent": enka.options.userAgent };
if (enka.options.githubToken && url.startsWith("https://api.github.com/"))
headers["Authorization"] = `Bearer ${enka.options.githubToken}`;
const requestConfig = {
headers,
transformResponse: res => res,
};
if (enableTimeout)
requestConfig.timeout = enka.options.requestTimeout;
const res = await (async () => {
try {
return await axios_1.default.get(url, requestConfig);
}
catch (e) {
if (typeof e === "object" && e && "response" in e)
return e.response;
else
throw e;
}
})();
if (res.status !== 200)
throw new Error(`Failed to fetch string from ${url}. Expected status code 200, but got ${res.status} - ${res.statusText}: ${res.data}`);
const result = res.data;
if (typeof result !== "string")
throw new Error(`Failed to fetch string from ${url}. Expected a string: ${result}`);
return res.data;
}
;