UNPKG

d-wiki

Version:

A JavaScript wrapper for the wikipedia apis

80 lines (79 loc) 2.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setUserAgent = exports.setAPIUrl = exports.returnRestUrl = exports.makeRestRequest = exports.setProxy = void 0; const axios_1 = require("axios"); const errors_1 = require("./errors"); const https_proxy_agent_1 = require("https-proxy-agent"); const axios_2 = require("axios"); let req = axios_2.default; let API_URL = "https://en.wikipedia.org/w/api.php?", REST_API_URL = "https://en.wikipedia.org/api/rest_v1/", // RATE_LIMIT = false, // RATE_LIMIT_MIN_WAIT = undefined, // RATE_LIMIT_LAST_CALL = undefined, USER_AGENT = "wikipedia"; async function callAPI(url) { const options = { headers: { "Api-User-Agent": USER_AGENT, }, }; try { const { data } = await req.get(url, options); return data; } catch (error) { throw new errors_1.wikiError(error); } } function setProxy(proxy) { const httpsAgent = new https_proxy_agent_1.HttpsProxyAgent(proxy); req = axios_1.default.create({ proxy: false, httpsAgent, }); } exports.setProxy = setProxy; // Makes a request to legacy php endpoint async function makeRequest(params, redirect = true) { const search = { ...params }; search["format"] = "json"; if (redirect) { search["redirects"] = ""; } if (!params.action) { search["action"] = "query"; } search["origin"] = "*"; let searchParam = ""; Object.keys(search).forEach((key) => { searchParam += `${key}=${search[key]}&`; }); return await callAPI(encodeURI(API_URL + searchParam)); } // Makes a request to rest api endpoint async function makeRestRequest(path, redirect = true) { if (!redirect) { path += "?redirect=false"; } return await callAPI(encodeURI(REST_API_URL + path)); } exports.makeRestRequest = makeRestRequest; //return rest uri function returnRestUrl(path) { return encodeURI(REST_API_URL + path); } exports.returnRestUrl = returnRestUrl; //change language of both urls function setAPIUrl(prefix) { API_URL = "https://" + prefix.toLowerCase() + ".wikipedia.org/w/api.php?"; REST_API_URL = "https://" + prefix.toLowerCase() + ".wikipedia.org/api/rest_v1/"; return API_URL; } exports.setAPIUrl = setAPIUrl; //change user agent function setUserAgent(userAgent) { USER_AGENT = userAgent; } exports.setUserAgent = setUserAgent; exports.default = makeRequest;